C/C++ header and implementation files: How do they work?

The header file declares functions/classes – i.e. tells the compiler when it is compiling a .cpp file what functions/classes are available.

The .cpp file defines those functions – i.e. the compiler compiles the code and therefore produces the actual machine code to perform those actions that are declared in the corresponding .hpp file.

In your example, main.cpp includes a .hpp file. The preprocessor replaces the #include with the contents of the .hpp file. This file tells the compiler that the function myfunction is defined elsewhere and it takes one parameter (an int) and returns an int.

So when you compile main.cpp into object file (.o extension) it makes a note in that file that it requires the function myfunction. When you compile myfunction.cpp into an object file, the object file has a note in it that it has the definition for myfunction.

Then when you come to linking the two object files together into an executable, the linker ties the ends up – i.e. main.o uses myfunction as defined in myfunction.o.

Leave a Comment