Summary - Compiler internals
- C++ course
- Expert
- Lesson 42/47
- 5 min
Combine AST, instantiation and linker to write a code analysis tool.
Summary - Compiler internals
In this group you saw the compiler internals: compilation phases, AST, template instantiation, linker and optimization. All turn source code into an executable.
Now you will combine them in a constexpr + function example. You will use constexpr int base = 10; and the add function together; this shows how compilation phases and optimization work together.
Compilation combination
When a program is compiled, the four phases run in order. constexpr int base = 10; survives preprocessing, enters the AST during compilation, gets constant-folded in optimization and is embedded into the executable as 10 during linking.
To see this combination: constexpr int base = 10; int add(int x) { return x + base; }. The compiler folds base directly into 10; the add(5) call returns 15 with optimized code. All this happens during compilation; it is ready at run time.
Practice Combine constexpr + add
Define constexpr int base = 10;. Write int add(int x) with body return x + base;. In main write std::cout << add(5);.
Starter code
#include <iostream>
// Define the base constexpr constant and the add function here
int main() {
// Call add and print it
return 0;
}Sample solution
#include <iostream>
constexpr int base = 10;
int add(int x) {
return x + base;
}
int main() {
std::cout << add(5);
return 0;
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which phase does the linker run?
g++ -c main.cpp // produces .o
g++ main.o -o program // linker- Preprocess
- Link (last phase) Correct answer
- Compile
- Run
Explanation: The linker is the last of the compilation phases.
2 Complete the template definition
template <typename ____> T identity(T x) { return x; }
template <typename T> T identity(T x) { return x; }
Explanation: typename T is the template type parameter.
3 Match each tool to its trait
| Term | Meaning |
|---|---|
preprocess |
#include handling |
AST |
Syntax tree |
instantiation |
Template instance |
linker |
Combines objects |