I'm trying to get my head around including a header file.
This is the source file for the function:
1 2 3 4
int add(int x, int y)
{
return x + y;
}
This is the header file I want to include:
1 2 3 4 5 6
#ifndef ADD_H_INCLUDED
#define ADD_H_INCLUDED
int add(int x, int y);
#endif // ADD_H_INCLUDED
And this is the main source file that I want to include it in:
1 2 3 4 5 6 7 8 9
#include <iostream>
#include "add.h"
usingnamespace std;
int main()
{
cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
return 0;
}
But when I compile and run it doesn't work! I get the error message "undefined reference to 'add(int, int)' "
I am using Code:Blocks and the header is a .h file. What is going wrong?
"What do I have to do to get main.cpp to work properly?"
Your main() is fine.
Your header shouldn't look like that. You had it right the first time. If the compiler fails to find the definition of a function, it means the source file in which the function is defined isn't visible. The only thing I can think of is that your "add.cpp" source file isn't part of the project. If this is the case, the compiler will no be able to compile it; thus, the linker will never see the definition; hence, the UES (Unresolved External Symbol) error.
In the "Management" pane on the left hand side, right click your project's name (it should be bold if it's active). Select the "Add files..." menu item. Then, locate the items.