CodeBlanks Logo Icon CodeBlanks

Compilation phases

Learn the C++ compilation phases.

Compilation phases

C++ compilation happens in four phases: preprocess, compile, assemble and link. Each phase takes the previous phase's output.

Preprocessing handles #include, #define and conditional compilation directives. Compilation turns the preprocessed source into machine-near assembly. Assembly turns the assembly into an object file (.o). Linking combines object files into an executable. This separation lets you understand which tool reports which error.

Phase details

Each phase's output is the next phase's input. Preprocessing turns a .cpp file into a .ii file; this file has all headers expanded. Compilation turns .ii into a .s (assembly) file. Assembly turns .s into a .o (object) file.

Linking takes multiple .o files, resolves symbols and produces an executable. g++ -E main.cpp does only preprocessing; g++ -S main.cpp goes up to compilation; g++ -c main.cpp goes up to assembly. These flags run each phase separately.

Practice Use a #define macro

Write #define ANSWER 42. In main write std::cout << ANSWER;.

Starter code

main.cpp
#include <iostream>

// Define the ANSWER macro here

int main() {
    // Print ANSWER
    return 0;
}

Sample solution

main.cpp
#include <iostream>

#define ANSWER 42

int main() {
    std::cout << ANSWER;
    return 0;
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In which phase are #include directives resolved?

main.cpp
#include <iostream>
int main() { ... }
  • Preprocess Correct answer
  • Compile
  • Link
  • Run

Explanation: Preprocessing handles #include and #define directives.

2 Complete the #define name

Question
#define ____ 42
Answer
#define ANSWER 42

Explanation: The ANSWER macro gets the value 42.

3 Match each phase to its role

Term Meaning
preprocess #include handling
compile .cpp → .s (assembly)
assemble .s → .o (object)
link .o → executable

All lessons in Expert