Compiling & Running
C++ is a compiled language: before your program can run, it has to pass through several distinct stages that turn human-readable source code into a native executable. Understanding this pipeline makes compiler errors far less mysterious.
The compile pipeline
Stage | What happens |
|---|---|
Preprocessing | Handles lines starting with |
Compilation | Translates the preprocessed C++ source into assembly language for the target CPU architecture. |
Assembly | The assembler converts assembly code into machine code, producing an object file ( |
Linking | The linker combines your object file(s) with library code (like the standard library) into a single executable. |
When you run a single command like g++ file.cpp -o program, the compiler driver runs all four stages for you automatically.
Compiling with g++
Given the hello.cpp file from the previous chapter, compile it with:
g++ hello.cpp -o program
This produces an executable named program (or program.exe on Windows) in the current directory. Run it with:
./program # On Windows: program.exe
Hello, World!
Common compiler flags
Flag | Meaning |
|---|---|
-Wall | Enables most useful warning messages — always turn this on. |
-Wextra | Enables additional warnings beyond |
-std=c++20 | Selects the C++ standard version to compile against (e.g. c++17, c++20). |
-O2 | Enables a solid level of compiler optimization for release builds. |
-g | Includes debug symbols so tools like gdb can map machine code back to source lines. |
A more complete compile command
g++ -std=c++20 -Wall -Wextra -g hello.cpp -o program
Reading a compiler error
Suppose you forget a semicolon:
broken.cpp
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl
return 0;
}broken.cpp: In function 'int main()':
broken.cpp:5:5: error: expected ';' before 'return'
5 | return 0;
| ^~~~~~Compiler errors follow a pattern: the file and line number (broken.cpp:5), a description of what went wrong, and often a caret (^) pointing at the exact location. Read the first error in a long list first — a single missing semicolon can cascade into dozens of confusing follow-on errors.