Let's start from the beginning.
If you have somethinf like that:
1 2 3 4 5 6 7 8 9
|
int funcA(int a, int b)
{
return 2 * funcB(a, b);
}
int funcB(int a, int b)
{
return a + b;
}
|
it gives you an error, because funcB defined after funcA and latter have no idea, what funcB is. To fix this you can use forvard declaration:
1 2 3 4 5 6 7 8 9 10 11
|
int funcB(int, int);
int funcA(int a, int b)
{
return 2 * funcB(a, b);
}
int funcB(int a, int b)
{
return a + b;
}
|
and it will work now, because funcA sees, that there is funcB which takes two ints and return an int
somewhere.
Then you split your programm in multiple files:
1 2 3 4 5 6 7 8 9 10
|
//a.cpp
int funcA(int a, int b)
{
return 2 * funcB(a, b);
}
//b.cpp
int funcB(int a, int b)
{
return a + b;
|
now you have the same problem. You can manually declare an funcB function in a.cpp, but imagine that you will manually declare all functions and classes from, say, iostream or math.h? You should create a header file for b.cpp and #include it in a.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
//b.cpp
int funcB(int a, int b)
{
return a + b;
//b.h
int funcB(int, int);
//a.cpp
# include "b.h"
//Now we know that we including funtions from b.h
//And most likely their implementations is in b.cpp
//if we just write a forward declaration
//we will have no idea where to find funcB implementation
int funcA(int a, int b)
{
return 2 * funcB(a, b);
}
|
Why shouldn't you have implementation in .h files? that because #include "smth.h" just dump content of smth.h file at include position.
The following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
//***
//c.h
int dooCoolStuff(int a)
{
return a + 1;
}
//a.cpp
#include "c.h"
//...
//b.cpp
#include "c.h"
//...
|
will be processed as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
//a.cpp
int dooCoolStuff(int a)
{
return a + 1;
}
//...
//b.cpp
int dooCoolStuff(int a)
{
return a + 1;
}
//...
|
and there you have an error: you cannot have two functions with same signature. You should move actual implementation to .cpp file and leave declaration in .h:
1 2 3 4 5 6 7 8
|
//c.h
int dooCoolStuff(int);
//c.cpp
int dooCoolStuff(int a)
{
return a + 1;
}
|
and code "***" wont have any errors.