On large C/C++ projects, compilation happens in stages. Instead of compiling all the files together, every single .cpp file is compiled as its own little unit. Once the final executable is being "linked", all these units are combined to form a program. There are a couple of reasons for doing it this way, one being speed (not having to recompile everything after a change), another the ability to separate or bundle and distribute sections of the code as libraries, or even "link" at the very last second using run-time libraries (DLLs).
So each .cpp file is independent, with the compiler having no knowledge of the contents of another .cpp file. But how then does the compiler know how to call functions from one file to the other? By reading the function declaration in the associated header file. Note that compiler only needs to know *how* to call the function, the actual function won't be available until the program is linked with the compiled file that contains the definition.
- Header files are for declarations, which "advertise" the functions you can call if you link with the corresponding .cpp file.
- The .cpp file is for the actual implementation of the functions, which is executed when a call is made.
Putting the function definition in a header can be dangerous. Example:
- Header "a.h" defines the function "int a()"
- Source "x.cpp" includes header "a.h"
- Source "y.cpp" includes header "a.h"
Now both x and y will compile just fine, independently from each other. But when the program is linked together, there are now two definitions of the same function (one for each file that included the header)! Your build will fail with a very confusing error.
The correct way:
- Header "a.h" declares the prototype "int a();"
- Source "a.cpp" defines the function "int a()"
- Source "x.cpp" includes header "a.h"
- Source "y.cpp" includes header "a.h"
When the program is compiled, x and y will know how to call "int a()", because they had the declaration from the header, and when the program is linked, there will be just one version of "int a()", namely the one from "a.cpp". Build successful.