Compilation Process

Understanding preprocessing, compilation, and linking

Interview Relevant: Important for understanding build systems

C++ Compilation Process

Unlike interpreted languages (like Python or JavaScript), C++ source code cannot be executed directly. It traverses a rigid, multi-stage pipeline to morph into an optimized native machine-code executable.

The Four Stages of Compilation

1. Preprocessing

Expands macros, handles #include directives by pasting file contents, and strips comments.

Source (.cpp) → Preprocessed Source (.i)

2. Compilation

Translates the pure C++ preprocessed code into lower-level assembly language specific to your CPU architecture.

Preprocessed Source (.i) → Assembly Code (.s)

3. Assembly

The assembler converts assembly instructions into raw machine code (binary zeros and ones) stored in Object files.

Assembly Code (.s) → Object File (.o / .obj)

4. Linking

Stitches together multiple Object files and external static/dynamic libraries to produce the final executable.

Object Files (.o) + Libraries (.dll/.so/.a) → Executable (.exe / a.out)

Modern Build Systems

Manually compiling multi-file projects using terminal commands becomes unstable rapidly. Build systems automate parsing, compiling, and linking reliably.

Make

Classic terminal automation utility natively available on Unix/Linux parsing raw Makefiles.

CMake Industry Standard

Cross-platform meta-build engine generating Makefiles or Visual Studio projects conditionally.

Ninja

Small, exceptionally rapid build system engineered specifically to accelerate large C++ architectures.

Code Examples

Compile each stage separately to understand the process.

bash
1# See each stage separately
2g++ -E main.cpp -o main.i    # Preprocessing
3g++ -S main.i -o main.s      # Compilation to assembly
4g++ -c main.s -o main.o      # Assembly to object
5g++ main.o -o main           # Linking
6
7# Or compile everything at once
8g++ -o main main.cpp

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In