C++ Headers – Why Use #include for cpp and h/hpp Files

headersinclude

Why does the source include a header and not also the other way around? I googled it but only found questions regarding the use of header files, how to include them but nowhere to say why it is like it is.
If the header is merely the declaration, how does the compiler know the definition only from it?
For example: take foo.cpp, bar.h, bar.cpp. This is what everybody does:
in foo.cpp:
#include "bar.h"
but the bar.cpp is not included neither in the bar.h or foo.cpp. That's why I deem logical that bar.cpp be included in bar.h and so, indirectly in foo.cpp.

Best Answer

Compilation of C and C++ code is done in two distinct steps.

In the first step, the source code in a single .c or .cpp file is compiled to object code. While compiling the file foo.cpp, the compiler needs to know that bar contains a method doSomething and what parameters that method expects and what return type it returns, but the compiler doesn't need to know exactly what the function does internally.
The compiler checks that the call in the code from foo.cpp matches how the function is declared (which is obtained by the #include "bar.h"), and then makes an annotation in the object code that at position X the function bar::doSomething is being called.

In the second step, all the source files that make up the application are linked together to create the final executable. At this point, the linker tries to replace the annotations that the compiler made in the object code with the actual address of the corresponding function. The linker is explicitly told which object files it should look at.
It is only at this point that the definitions of all functions need to be available.

Which files are needed to create an application is typically defined in a project file or a makefile.