Header file help?

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"
using namespace 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?
closed account (zb0S216C)
You need to #include the header into the source file where the definition of add() resides.

Wazzak
Last edited on
So in add.cpp I have
1
2
3
4
5
6
#include "add.h"

int add(int x, int y)
{
    return x + y;
}


It still doesn't work
closed account (zb0S216C)
Is the source file part of the project? That is, is it included in your project tree?

Wazzak
I have add.cpp, main.cpp and add.h

What do I have to do to get main.cpp to work properly?

My latest effort is to have 2 files. Main.cpp which looks like this:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "add.h"
using namespace std;

int main()
{
    cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
    return 0;
}


and add.h which looks like this :
1
2
3
4
5
6
7
8
9
10
11
int add(int x, int y)
{
    return x + y;
}

#ifndef ADD_H_INCLUDED
#define ADD_H_INCLUDED

int add(int, int);

#endif // ADD_H_INCLUDED 


and this all works fine but firstly I don't understand why and secondly is it the right way of doing things?
closed account (zb0S216C)
Amnesiac wrote:
"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.

Wazzak
How do I make all the files part of the project in codeblocks?
closed account (zb0S216C)
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.

Wazzak
Cheers I was being a complete idiot.
Topic archived. No new replies allowed.