Reputation: 121
I'm currently learning C++ from a book called Alex Allain - Jumping into c++, and i got stuck at chapter 21. It details the C++ build process and i got it, except 2 parts:
First:
"The header file should not contain any function definitions. If we had added a function definition to the header file and then included that header file into more than one source file, the function definition would have shown up twice at link time. That will confuse the linker."
Second:
"Never ever include a .cpp file directly. Including a .cpp file will just lead to problems because the compiler will compile a copy of each function definition in the .cpp file into each object file, and the linker will see multiple definitions of the same function. Even if you were incredibly careful about how you did this, you would also lose the time-saving benefits of separate compilation."
Can somebody explain them?
Upvotes: 0
Views: 127
Reputation: 409166
A C++ program is created from one or more translation units. Each translation unit (TU for short) is basically a single source file with all included header files. When you create an object file you are actually creating a TU. When you are linking, you are taking the object files (TUs) created by the compiler and link them with libraries to create an executable program.
A program can only have a single definition of anything. If you have multiple definitions you will get an error when linking. A definition can be a variable definition like
int a;
or
double b = 6.0;
It can also be a function definition, which is the actual implementation of the function.
The reason you can only have a single definition is because these definitions are mapped to memory addresses when the program is loaded to be executed. A variable or a function can not exist in two places at once.
This is one of the reasons you should not include source files into other source files. It is also the reason you should not have definitions in header files, because header files could be included into multiple source files as that would lead to the definition being in multiple TUs.
There are of course exceptions to this, like having a function being marked as inline
or static
. But that is solved because these definitions are not exported from the TU, the linker doesn't see them.
Upvotes: 1