![]() |
VOOZH | about |
The process of converting human-readable C++ code into an executable machine program involves multiple stages. Each stage plays a critical role in ensuring that our code runs as intended.
We'll walk through the entire C++ compilation process, step-by-step, from source code to executable.
Source code is the C++ code that the programmer writes. It usually consists of:
Note: In the above example, math_utils.h is assumed to be a user-defined header file that contains the declaration (and corresponding definition in a separate .cpp file) of the add() function. It is not part of the C++ standard library and must be created separately for the program to compile successfully.
The preprocessor handles lines that start with # (like #include, #define, etc.) and prepares the code for the compiler. It:
g++ -E main.cpp -o main.i
Output: The output (main.i) contains pure C++ code with all header files inserted and macros expanded.
Example:
The compiler translates preprocessed C++ code into assembly language, which is human readable low-level code, It :
Command:
g++ -S main.i -o main.s
Output: main.s contains low-level assembly instructions.
Example: C++
Assembly:
The assembler converts the assembly code into object code, which is machine-readable binary (.o file).
Command:
g++ -c main.cpp -o main.o
Output: A .o (object file) that contains machine code, not yet executable on its own
The linker combines multiple object files (main.o, math_utils.o) and links in external libraries (like iostream), creating a final executable. It:
Command:
g++ main.o math_utils.o -o main
An executable file (usually called main or whatever name you give)
It is the final executable produced by the linker.
Command
./main
Output
Result: 15
Stage | Tool | Example command |
|---|---|---|
Preprocessing | g++ -E | g++ -E main.cpp -o main.i |
Compilation | g++ -S | g++ -S main.i -o main.s |
Assembly | g++ -c | g++ -c main.s -o main.o |
Linking | g++ | g++ main.o -o main |
Automation | make | Automate multi-file builds |
Stage | Common Errors |
|---|---|
Preprocessing | Header not found, macro errors |
Compilation | Syntax errors, type mismatches |
Assembly | Rare, but architecture-specific errors |
Linking | Undefined references, missing symbols |
Execution | Segmentation faults, logic bugs |