The Compilation Model: Preprocess, Compile, Link in C++
Building a C++ program is a three-stage pipeline hidden behind the single g++ command. First the preprocessor handles # lines: it pastes headers in, expands macros, and strips comments. Then the compiler translates each .cpp file independently into an object file of machine code. Finally the linker stitches object files and libraries together into one executable.
Knowing the stages turns cryptic errors into easy ones: undefined reference is a linker error (declared but never defined or not linked in), while syntax and type errors come from the compiler stage. Headers (.h) carry declarations; source files (.cpp) carry definitions β splitting them is what makes multi-file projects possible.
Preprocessing
#include pastes header text in, #define expands macros, and conditional blocks like #ifdef select code β the output is still C++ source, just bigger.
Compilation
Each .cpp file compiles separately into a .o object file. Syntax errors, type mismatches, and unknown names all fail here.
Linking
The linker combines object files and libraries into the final executable, resolving every function call to an actual definition.
Headers vs sources
Headers declare what's available (function signatures, class layouts); .cpp files define what things do. Including a header without ever defining its functions causes a linker error, not a compiler error.
// math.hpp: int square(int x); (declaration)// math.cpp: int square(int x) { return x * x; } (definition)// main.cpp: #include "math.hpp" ... square(6) ...// Build: g++ main.cpp math.cpp -o appRecommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.