I have been following the tutorials on the website and came to the subject of making and including one's own headers. However, when I write the basic addition program given, I get errors...
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include "add.h"
int main()
{
usingnamespace std;
cout << "the sum of 3 and 4 is " << add(3,4) << endl;
system ("pause");
return 0;
}
and the header add.h
1 2 3 4 5 6
#ifndef ADD_H
#define ADD_H
int add(int x, int y);
#endif
I get this error in the add.cpp file:
[linker error] endefined reference to 'add(int, int)'
Id returned 1 exit status
The code is written exactly as it is in the tutorial, but is there something I'm missing? I'm using devc++ 4.9.9.2.
I know this is probably a noobish question, but I am new to programming, basically, and have only worked within a single file so far.
well, the implementation of int add(int x, int y); ist missing
you can write something like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include "add.h"
// can be in another file
int add(int x, int y) // <---- this is the implementation
{
return (x + y);
}
int main()
{
usingnamespace std;
cout << "the sum of 3 and 4 is " << add(3,4) << endl;
system ("pause");
return 0;
}
It is a compiler dependant thing.At least in Borland C++ builder you just have to write your function in a new .cpp file and build the project as a whole.Your code itself is perfect,it just depends on where you defined your function and how are you compiling the files.If you can't find a solution,another option is to write an inline function inside the header.Cheers.
That fixed it coder777. Should submit that solution to the tutorial author, I guess? So a header file is like any other file, you have to initialize a function and then actually tell it what to return, correct? It seems obvious now, but I hadn't seen a reference to that necessity before and thought maybe a header operated differently.