Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 171 ยท Getting Started

How C++ Works: Compiling and Linking

Follow C++ code from source to executable through the preprocessor, compiler and linker. Meet GCC, Clang, MSVC, C++ standards, warnings and UB.

C++ is a compiled language. Before your program can run, a tool called a compiler translates your source code into machine code, the raw instructions your processor understands. The result is an executable: a standalone program that runs directly on the operating system, with no interpreter or virtual machine in between.

That's a big difference from languages like Python or JavaScript, where an interpreter reads your code while it runs. Compiling ahead of time is a large part of why C++ is fast, and it also means many mistakes are caught before the program ever starts. In this lesson you'll follow a program through every step of the build, meet the main compilers and C++ versions, and learn why turning on warnings is one of the best habits you can build.

From source code to executable

When you press Run in our editor, or type a build command on your own computer, your code passes through four stages:

TEXT
main.cpp โ”€โ”€โ–บ preprocessor โ”€โ”€โ–บ compiler โ”€โ”€โ–บ main.o โ”€โ”€โ–บ linker โ”€โ”€โ–บ program (executable)
 (source)    (text pasting)   (to machine   (object       (joins files
                               code)         file)         and libraries)

Strictly speaking, the "compiler" program you run (like g++) drives all four stages for you. But each stage has a distinct job, and knowing them helps you understand the error messages each one produces.

1. The preprocessor

The preprocessor works on plain text before any real compilation happens. It handles the lines that start with #, called directives:

  • #include <print> is replaced by the entire contents of the <print> header file (and everything that header includes in turn). A tiny program can grow to tens of thousands of lines after this step.
  • #define NAME value creates a macro: every later occurrence of NAME is replaced by value.
  • #if, #ifdef and #endif keep or remove chunks of code depending on conditions, which is how code adapts to different compilers or platforms.

The output of this stage is called a translation unit: one big file of pure C++ with no # directives left. The compiler also defines some macros for you, and you can print them to learn about your build:

C++ What the preprocessor knows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The preprocessor replaces __cplusplus with a number that identifies the language version: 202302 means C++23. __GNUC__ and friends exist only in GCC (and Clang, which imitates them), and __LINE__ becomes the line number where it appears, 6 here. The #ifdef block keeps only one of the two println lines; the other never reaches the compiler at all.

Note: Modern C++ uses macros far less than older code did. Constants, functions and templates do the same jobs with real type checking. You'll still need #include until C++20 modules (import std;) are widely supported by build tools; that's covered in a later lesson.

2. The compiler

The compiler proper reads the translation unit, checks that it's valid C++, and translates it into machine code. This is where most errors you'll see come from:

  • Syntax errors: a missing semicolon, an unclosed brace.
  • Type errors: adding a number to something that isn't a number, calling a function with the wrong arguments.
  • Name errors: using a variable or function the compiler has never heard of.

The compiler also optimizes: it rearranges, removes and simplifies your code so it runs faster, while keeping the observable behavior the same. A loop that sums constants might be replaced by the final answer.

The output for each .cpp file is an object file (main.o on Linux and macOS, main.obj on Windows). It contains machine code, but it's not a program yet: it may still call functions that live in other files or libraries.

3. The linker

Real projects have many .cpp files, each compiled separately into its own object file. The linker combines all object files, plus the libraries they use (like the C++ standard library), into a single executable. Its main job is to connect every use of a function to the place where that function is defined.

If a function is declared but never defined anywhere, the compiler is happy (it trusts the declaration), but the linker can't find it. Run this example to see a linker error. It's meant to fail:

C++ A linker error (on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output contains the key line undefined reference to `square(int)', followed by ld returned 1 exit status. ld is the name of the linker. Notice there's no line number pointing into your code: linker errors are about whole files and missing definitions, not about a particular line. Fix it by adding a definition below main:

C++
int square(int n) {
    return n * n;
}

Run it again and it prints 25. You'll split programs into several files in the header files lesson; for now, every program lives in one file.

4. Running the executable

After linking, you have a program file. On your own computer you'd run it from a terminal (./program on Linux and macOS, program.exe on Windows). The operating system loads it into memory and calls main. When main returns, its value becomes the program's exit code, which scripts and other programs can check: 0 means success and anything else means some kind of failure.

Compilers: GCC, Clang and MSVC

C++ isn't owned by one company. It's an international standard (ISO/IEC 14882), and several independent compilers implement it. The big three are:

Compiler Command Typical platforms Notes
GCC (GNU Compiler Collection) g++ Linux, also Windows (MinGW) and macOS Free and open source; the standard compiler on Linux. Our editors use GCC 15.2.
Clang (LLVM project) clang++ macOS (the default with Xcode), Linux, Windows Free and open source; known for clear error messages and great tooling.
MSVC (Microsoft Visual C++) cl Windows Ships with Visual Studio; the usual choice for Windows desktop apps and many games.

All three support nearly all of C++20 and a large part of C++23 in their current versions. Code that sticks to standard C++ compiles on all of them; compiler-specific extensions (like __GNUC__ above) are the exception. Professional projects often build with two or three compilers to catch portability problems early.

C++ standards: from C++98 to C++26

The C++ committee releases a new version of the language every three years. Each version is named after its year:

Standard Highlights
C++98 / C++03 The first ISO standard: classes, templates, exceptions, the STL containers and algorithms.
C++11 The "modern C++" revolution: auto, range-based for, lambdas, move semantics, smart pointers, threads.
C++14 Polish: generic lambdas, std::make_unique, relaxed constexpr.
C++17 Structured bindings, std::optional, std::variant, std::string_view, if with initializer, the filesystem library.
C++20 Concepts, ranges, coroutines, modules, std::format, std::span, the <=> operator.
C++23 std::print/std::println, std::expected, more ranges, std::generator, import std;.
C++26 The newest standard (technical work finished in March 2026; ISO publication follows): static reflection, contracts, std::execution and more. Compilers are still adding support.

New standards almost never break old code, so a C++98 program usually still compiles today. That's great for stability, but it means C++ carries a lot of history. This course teaches the modern features first and shows older styles only so you can recognize them and know why they've been replaced.

Compiler flags and warnings

You control a compiler with flags (also called options). On your own machine, a typical GCC or Clang command for a single-file program looks like this:

Terminal
g++ -std=c++23 -Wall -Wextra -O1 main.cpp -o program
./program
Flag Meaning
-std=c++23 Compile as C++23. Without it, you get the compiler's default (C++17 with GNU extensions for current GCC).
-Wall -Wextra Turn on a large set of useful warnings. Despite its name, -Wall is not "all" warnings.
-O1, -O2, -O3 Optimization levels. -O0 (the default) is easiest to debug; -O2 is a common release setting.
-g Include debugging information so a debugger can show your source lines.
-o program Name of the output file.

These are exactly the settings our editors use: C++23, -Wall -Wextra and -O1. With MSVC the equivalents are /std:c++latest, /W4 and /O2.

A warning means "this is valid C++, but it looks like a mistake". The program still compiles and runs, but you should read and fix every warning. Run this example and look at the two warnings above the output:

C++ Warnings point at likely bugs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC reports that discount is never used (-Wunused-variable), which often means you forgot to apply it, and that the loop compares a signed int with an unsigned size (-Wsign-compare), a classic source of subtle bugs you'll study in Integer Types. Each warning names the flag that enabled it in square brackets, along with the line and column. Many teams add -Werror, which turns every warning into an error so nobody can ignore them.

Tip: Treat warnings as free code review. Professionals compile with warnings on from day one, because fixing ten warnings now is far easier than hunting one mysterious bug later.

Installing a toolchain on your computer

You can do this whole course in the browser, but you'll eventually want C++ on your own machine. The compiler, linker and standard library together are called a toolchain. Here are the usual ways to get one:

  • Windows: install Visual Studio Community (free) and select the "Desktop development with C++" workload. It includes MSVC, a debugger and an IDE. Alternatively, install GCC through MSYS2, which gives you g++ in a terminal.
  • macOS: run xcode-select --install in Terminal to get Apple Clang. For the newest C++23 features, install LLVM Clang or GCC with Homebrew (brew install llvm or brew install gcc).
  • Linux: use your package manager, for example sudo apt install g++ on Ubuntu or Debian, or sudo dnf install gcc-c++ on Fedora.

Check what you have with:

Terminal
g++ --version
clang++ --version

For an editor, Visual Studio Code with the C/C++ extension, CLion and Visual Studio are popular choices. Larger projects use a build system such as CMake to run the compiler for you; you'll meet it in Build Systems: Make and CMake.

Undefined behavior in one paragraph

C++ trusts you. Some operations, like reading past the end of an array, using a variable you never gave a value, or letting a signed integer overflow, are not errors the compiler must catch. Instead, the standard says their result is undefined behavior (UB): the program may crash, print garbage, seem to work today and fail tomorrow, or behave differently with another compiler or optimization level. The optimizer is allowed to assume UB never happens, so the effects can be truly strange. This is the price of C++'s speed. Modern C++ gives you tools to avoid UB almost entirely (containers, at(), smart pointers, warnings and sanitizers), and you'll learn them throughout the course, with a full lesson on undefined behavior later.

Seeing optimization at work

Optimization doesn't change what your program does, only how fast it does it. In this example the compiler is free to compute the sum while compiling, so the finished program might just print a stored number:

C++ The result is the same at any -O level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output is 500000500000 whether the loop actually runs a million times or the compiler replaced it with the answer. (The ' in 1'000'000 is a digit separator that just makes the number easier to read.) Correct programs give the same result at every optimization level; programs with undefined behavior often don't, which is one way UB reveals itself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which build stage replaces #include <print> with the contents of the header?

    Lines starting with # are directives for the preprocessor, which pastes in header files and expands macros before compilation.
  2. 2. A program declares int area(int w, int h);, calls it in main, but never defines it. What happens?

    The declaration satisfies the compiler, but the linker must find a definition to connect the call to. Without one, it fails with "undefined reference to area(int, int)".
  3. 3. What is true about a compiler warning?

    Warnings flag legal code that looks suspicious, like unused variables or signed/unsigned comparisons. With -Werror they become errors.
  4. 4. What does the flag -std=c++23 do?

    The -std= flag picks the language standard. Our editors compile as C++23 so features like std::println are available.
  5. 5. Which statement about undefined behavior is correct?

    Undefined behavior has no guaranteed result. It can look fine in testing and break later, which is why modern C++ habits focus on avoiding it.

Summary

  • C++ is compiled ahead of time into a native executable: preprocessor โ†’ compiler โ†’ object files โ†’ linker โ†’ program.
  • The preprocessor handles #include, #define and #if; the compiler checks and translates code into object files; the linker joins object files and libraries and resolves every function call.
  • Linker errors ("undefined reference") mean a definition is missing, not that a line is wrong.
  • The main compilers are GCC, Clang and MSVC; C++ is an ISO standard with a new version every three years (C++11 through C++23, with C++26 arriving now).
  • Compile with -std=c++23 -Wall -Wextra and treat warnings as bugs waiting to happen.
  • Undefined behavior has no defined result; modern C++ tools and habits help you avoid it.

Next: C++ Syntax, where you'll learn the rules for writing statements, blocks, includes and namespaces.