C++ · Module 1 · Lesson 41 min read

How a C++ Program is Built

The build pipeline

scss
hello.cpp → [Preprocessor] → [Compiler] → [Assembler] → hello.o → [Linker] → hello (executable)

1. Preprocessing

Handles lines beginning with #:

  • #include copies the contents of header files in
  • #define macros are replaced
  • #if/#ifdef removes code conditionally See it: g++ -E hello.cpp (iostream alone adds tens of thousands of lines!)

2. Compilation

Checks syntax and types and translates C++ into assembly. Most errors come from here. See it: g++ -S hello.cpp

3. Assembly

Turns assembly into machine code in an object file (.o / .obj). g++ -c hello.cpp stops here.

4. Linking

Combines your object files with libraries (like the C++ standard library) into one executable. "undefined reference" errors come from the linker: you declared something but never defined it.

Multiple files

CSS
g++ -c main.cpp        → main.o
g++ -c math.cpp        → math.o
g++ main.o math.o -o app

Only changed files need to be recompiled (this is what build tools like Make and CMake automate — Unit 17).

Compile time vs run time

  • Compile time: when the compiler works (type errors, syntax errors)
  • Run time: when the program runs (division by zero, wrong input) C++ does lots of checking at compile time — errors found early are cheap.

Useful flags summary

-std=c++20 standard · -Wall -Wextra warnings · -g debug info · -O2 optimize · -c compile only · -o name output name · -E preprocess only

Example

C++
#include <iostream>

#define APP_NAME "BudgetBuddy"     // replaced by the preprocessor
#define DEBUG_MODE 1

int main() {
    std::cout << "App: " << APP_NAME << '\n';

#if DEBUG_MODE
    std::cout << "Debug build: extra checks enabled\n";   // kept by the preprocessor
#else
    std::cout << "Release build\n";                        // removed before compiling
#endif

    // These macros are filled in by the compiler
    std::cout << "This line is in file " << __FILE__ << ", line " << __LINE__ << '\n';
    return 0;
}

/* Output:
App: BudgetBuddy
Debug build: extra checks enabled
This line is in file main.cpp, line 16
*/