Header/Source Organization and Compilation
How a C++ program is split across files, and how the compiler turns it into a runnable binary
- tell a declaration apart from a definition and state the One Definition Rule,
- split a component into a
.hheader and a.cppsource file, - trace a build through preprocess, compile, and link,
- protect a header with an include guard or
#pragma once, - decide what belongs in a header versus a source file.
1. Why split code across files?
Think of a large cookbook. The table of contents lists every dish by name and page: it tells you what exists without printing the recipe again. The recipe pages hold the actual steps. Two cooks in different kitchens can both read the same table of contents, agree on which dishes exist, and each cook their part.
C++ works the same way. A header (.h or .hpp) is the table of contents: it announces the names, types, and shapes of functions and classes. A source file (.cpp) is the recipe page: it contains the working code. Every .cpp that wants to use a function just #includes the header, trusts that a definition exists somewhere, and gets on with its own job.
This split buys you three things: faster builds (change one .cpp and only that file recompiles), reuse (many files share one header), and clear interfaces (the header is the public contract; the source is the private implementation).