What happens if more than one .cpp file is included?
Becase I've seen (and used) situations like this:
In header.h:
class point
{
public:
point(xpos, ypos);
int x;
int y;
};
In def.cpp:
#include"header.h"
point::point(xpos, ypos)
{
x = xpos;
y = ypos;
}
In main.cpp:
#include"header.h"
int main()
{
point p1(5,6);
return 0;
}
I know the program is executed from main, but how does the compiler know which order to compile the .cpp files? (In particular, if you have multiple non-networked .cpp files).
the compiler doesn't matter - it compiles each .cpp file to an .obj file, and the .obj files contain a list of missing characters. So, in this case, main.obj says "I'm missing point::point
".
The linker is then executed to take all the .obj files, concatenate them into an executable file, and ensure that each .obj file is missing from one of the other .obj files - hence the term "linker".
a source to share
If you include them in two different cpp files, this is not a problem. If you include the same header twice, you get errors for duplicate definitions.
You have to use the included guards to get around this.
At the top of the file, before any code:
#ifndef HEADER_H_ //every header gets it own name
#define HEADER_H_
Down below:
#endif
a source to share
Usually you compile them yourself (or with a build tool like make
). The header file allows you to compile them in any order. If you compile them together, the order is probably the order you pass to the compiler command, but it doesn't really matter, they all end up linked to the same executable.
a source to share
This is why you see #ifndef HEADER_H and #define HEADER_H at the top of some header files. The concept of only one inclusion of each header file as described here , for example.
a source to share