CppCompiling & Running

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 #, like #include and #define. Headers get textually inserted, macros expanded.

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 (.o / .obj).

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:

Bash
g++ hello.cpp -o program

This produces an executable named program (or program.exe on Windows) in the current directory. Run it with:

Bash
./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 -Wall for extra safety.

-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

Bash
g++ -std=c++20 -Wall -Wextra -g hello.cpp -o program
Reading a compiler error

Suppose you forget a semicolon:

broken.cpp

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.

Compiling multiple files
Real projects split code across several `.cpp` files. You can compile them together in one command, e.g. `g++ main.cpp math.cpp -o program` — the compiler builds each into an object file and the linker combines them.