#include "StdAfx.h"
#include "people.h"
people::people(void)
{
}
people::~people(void)
{
}
int sum(int a, int b)
{
int result;
int result = a + b;
return result;
}
I try to use my function sum() in my main method. But it says "Error:identifier "sum" is undefined. I tried to put "int" infront, then my comma gets an error "Error: expected a')'"
At that line in your main function, the function "sum" does not exist.
This is because it has not been declared anywhere, or defined. You have defined a function called sum in what I assume is your people.cpp file, but your main code cannot see that. Your main code can see the header file, which also does not declare or define a function called sum (although you do declare a class function within your people class called sum, but sum(3,4);
is not trying to use that class function).
Solution; add declaration of the sum function, like this,
int sum(int a, int b);
to the top of your main code file (sorry, I don't know what you've called it, that one with _tmain in) or to your people.h file
It is true that you haven't initialised your people object, but you're also not even trying to create one or use one.
// main.cpp
#include <iostream>
#include "sum.h"
int main ()
{
int x;
x = sum(3,4);
std::cout << x;
return 0;
}
1 2 3 4
// sum.h
//declare sum function
int sum(int a, int b);
1 2 3 4 5 6 7
// sum.cpp
//define sum function
int sum(int a, int b)
{
return(a+b);
}
I've not compiled it to test, but it should give you an idea of how this works. Be sure you compile both sum.cpp and main.cpp in your project.
Edit: I have now compiled and tested, and on my system at least this is happy. Hopefully this makes it clear how to go about doing this. I think you were confusing yourself by having that unused "people" class in there
I don't think you quite understand what a class is for. There is no need at all for you to be defining a class if you're not going to use a function from within it.
That's right. This is not Java; you do not have to have a class containing every function you ever use, and you don't even use the class in this case anyway.