C++: the essentials

What every reader of the C++ pages needs first: who decides when an object dies, how a program is built from separately compiled files, undefined behaviour and the tools that catch it, libraries, which standard to ask for, the mistakes that cut across the language, and the map of the four child pages. Every output is a real run on an Apple M1 Pro. Data as of October 2026. Reading: 21 min, plus 9 in closed details.

The idea in one screen

In C++ you decide where each object lives and when it dies, and the compiler trusts you: each file is compiled separately and the pieces are linked, and a broken rule is undefined behaviour, not an error. Python decides both things for you, which is why C++ is fast where you take care and silently wrong where you do not.

Fig. 1 follows one small program from its source files to the machine, in the order the pieces meet it. Each step names the section of this page, or the child page, that owns that piece, and links the child's own figure instead of drawing it again. Every number is from a recorded run on this page.

  1. Three source files. main.cpp (7 lines) calls count_tokens, tokens.h (4 lines) declares it, tokens.cpp (14 lines) defines it. Nothing runs yet: C++ has no run-time import, so a separate build turns them into a program (section 1).
  2. The preprocessor pastes. Each #include copies a whole file in, so main.cpp plus tokens.h plus the standard headers becomes one translation unit of 55,693 lines; tokens.cpp's is 55,700. Heights in the figure are on a log scale. Modules, the cure, are section 4.
  3. Each file compiles alone. Each translation unit becomes an object file of machine code and symbols: main.o (928 bytes) needs count_tokens (U), tokens.o (848 bytes) defines it (T). The compiler accepted main.cpp on the header's promise; section 1's stepper shows each stage.
  4. The linker joins. It matches every U to exactly one T and writes app (33,696 bytes). libc++ and libSystem stay outside it, loaded when the program starts: dynamic libraries (section 3).
  5. Run: one owner on the stack, its buffer on the heap. std::vector<float> v{1, 2, 3}: v itself is 24 bytes on the stack (pointer, size, capacity) and its three floats are 12 bytes on the heap, measured with a replaced operator new. Owner: Ownership, moves and lifetimes, whose stack and heap figure replays a real run with a copy and a move.
  6. The closing brace frees. ~vector() runs at the brace: the heap bytes are freed, then v vanishes with its frame. One owner, one moment, no garbage collector: that is RAII (the ownership page, section 3). The vector itself is a class template from the standard library; how it grows its buffer is the vector figure on Classes, templates and the standard library.
  7. Two owners, one buffer: undefined behaviour. Swap the vector for a class with only a destructor: its compiler-written copy copies the pointer, so a and b own one 16-byte array and both free it. At -O0 the program crashed (exit code 133); at -O2 it printed "same array: 1" and exited normally; ASan reported "attempting double-free". No error from the compiler: section 2 and its gallery.
  8. To the CPU. Every load climbs a ladder of caches, DRAM to L2 to L1 to a register, one cache line at a time, so layout sets speed: summing a matrix by columns ran 52 to 56 times slower than by rows. Owner: The machine underneath, whose cache ladder figure times each level on this M1 Pro.
  9. All of it in one engine. llama.cpp is every piece at once: a CMake build with vendored libraries, model weights mapped from a file and repacked at load, a graph walked by threads through SIMD kernels. Owner: Reading llama.cpp, whose Fig. 1 times one token through it.

You need: everyday Python. Nothing about C++ beyond having seen its syntax; each child page names what it assumes from this one.

translation unit
one .cpp file after the preprocessor has pasted in its headers; the compiler sees only this
object file, symbol
a compiled translation unit (.o) and the names it defines or needs
linker
joins object files and libraries into one program, one definition per symbol
ODR
the one definition rule: one definition of each function in the whole program
undefined behaviour (UB)
an operation the standard gives no meaning; the optimiser assumes it never happens
sanitizer
a compiler mode that adds run-time checks for one family of UB (ASan, UBSan, TSan)
ABI
the binary contract (layouts, calling convention, names) that compiled pieces must share

Six ideas, and where each is taught

C++ is the language underneath most of the ML stack you use from Python: PyTorch's core, llama.cpp, ONNX Runtime, the CUDA kernels. The whole language follows from one decision: C++ gives you the machine's own representation of data and makes you responsible for how long each piece of it lives. Python decides both for you; Fig. 2 shows the difference on one vector. Six ideas follow from that:

In PythonIn C++Why C++ does it this wayTaught on
You run the source fileA compiler turns each .cpp file into machine code, then a linker joins the pieces into one programMachine code runs without an interpreter, so loops cost nanoseconds, not tens of nanosecondsSection 1
b = a makes a second name for the same objectauto b = a; makes a copy; you ask for a reference (&) or a pointer (*) explicitlyValues sit inline in memory, with no per-object header or reference countOwnership, section 1
Every object lives on the heap until the last reference goesLocal variables live on the stack and die at the closing brace; you choose the heap when you need itThe stack is free to allocate and freeOwnership, section 2
with open(...) for cleanupRAII: every object's destructor runs at a known moment, so every resource is released by oneDeterministic cleanup with no garbage collectorOwnership, sections 3 and 4
Assignment never copies a big objectMove semantics: a value can hand its heap buffer to another instead of being copiedCopy by default would otherwise make returning a vector expensiveOwnership, sections 5 to 7
Bugs raise exceptionsMany bugs are undefined behaviour: no error, the program means nothing, and the optimiser may make it do anythingChecking every index and every overflow would cost speed; C++ checks only when you askSection 2

The rest is the toolkit you write with (classes, templates, the standard library, lambdas, errors: the classes page), what the CPU does with it (the machine page), and one real codebase read end to end (the llama.cpp page).

Fig. 2 · One vector of three floats: in C++ a 24-byte owner on the stack and 12 bytes on the heap, freed at the closing brace; in Python a name, a counted list and three float objects
C++: { std::vector<float> v{1, 2, 3}; ... }
stack (the block's frame)heap v24 bytes, the owner data ● size 3 capacity 3 1.0 2.0 3.0 12 bytes: 3 floats of 4 At the closing brace, ~vector() runs: the 12 bytes are freed, then v's 24 bytes vanish with the frame. One owner, one moment. Measured: new 12 bytes, delete at the brace.
Python: v = [1.0, 2.0, 3.0]
namesheap objects v list: 88 B refcount 1 type: list items ●●● 3 pointers of 8 B 1.0 (24 B) 2.0 (24 B) 3.0 (24 B) three float objects Freed when the count reaches 0: whenever the last reference goes, which the interpreter tracks; no brace decides it. Measured: sys.getsizeof on CPython 3.14.8.

The same three numbers cost 12 bytes in C++ and 88 + 3 × 24 = 160 bytes in Python, and only C++ lets you point at the line where they are freed. Every rule on these pages follows from owning that moment: who frees, when, and what if two owners free the same bytes (the double free, section 2).

The real runs behind the figure (Apple clang 17 and CPython 3.14.8, M1 Pro, 2026-10-26)
vector.cpp (lines 22 to 32)
int main() {
    trace = true;
    std::printf("{  enter the block\n");
    {
        std::vector<float> v{1.0f, 2.0f, 3.0f};
        std::printf("  v itself: %zu bytes on the stack at %p (pointer, size, capacity)\n", sizeof v, (void*)&v);
        std::printf("  v.data(): %zu floats of %zu bytes on the heap at %p\n", v.size(), sizeof(float), (void*)v.data());
        std::printf("}  leave the block: v's destructor runs now\n");
    }
    std::printf("after the block: nothing is left to free\n");
}
$ clang++ -std=c++23 -O2 -Wall -Wextra vector.cpp -o vector && ./vector
{  enter the block
  operator new: 12 bytes on the heap at 0x105151410
  v itself: 24 bytes on the stack at 0x16b1d6638 (pointer, size, capacity)
  v.data(): 3 floats of 4 bytes on the heap at 0x105151410
}  leave the block: v's destructor runs now
  operator delete: heap 0x105151410 freed
after the block: nothing is left to free
$ python3.14 vector.py
v is a name bound to a list object: 88 bytes on the heap
the list holds 3 pointers; each points at its own float object of 24 bytes
references to the list: 1 (the name v); it is freed when that count reaches 0
after del v: the count reached 0 and CPython freed the list (no destructor call you can see)

The C++ program replaces the global operator new and operator delete to print every heap allocation, so the line where the buffer is freed is visible. The addresses change from run to run; the stack address is far from the heap's.

Six things the runs showed

Every output, compiler error, sanitizer report and number on these pages comes from a real run on an Apple M1 Pro (2026-10-05, reruns 2026-10-26; LLVM clang 23 for the sanitizers, Apple clang 17 otherwise; llama.cpp pinned at commit 8e16421).

FindingWhere it is shown
The optimiser changes what buggy code does: a double free crashed at -O0 and vanished at -O2; a data race lost updates at -O0 and gave the right answer at -O2 by luck. Sanitizers catch both.The UB gallery, here
An exception is free until thrown: throwing and catching one cost about 4.8 µs; returning a std::expected about 1 ns.Classes, templates and the standard library, section 6
Summing a matrix by columns was 52 to 56 times slower than by rows: same arithmetic, different cache behaviour.The machine underneath, section 2
Two threads writing counters on the same cache line ran 21 to 22 times slower; padding to 64 bytes still left about 2x, because this M1's lines are 128 bytes.The machine underneath, section 8
On Apple Silicon with the default build, the ggml_vec_dot_* kernels most guides tell you to read run zero times: weights are repacked at load and 4x4 gemv/gemm kernels do every product.Reading llama.cpp, section 10
For a model this small, Metal generated tokens more slowly than 4 CPU threads: launching many tiny GPU kernels per token costs more than the work.Reading llama.cpp, section 13

1. How a C++ program is built

Python reads your source and runs it; import tokens finds tokens.py at run time. C++ has no run-time import. Building is a separate step with three stages, and most confusing C++ errors come from not knowing which stage complained.

  1. Preprocessor. Lines starting with # are text commands. #include "tokens.h" pastes the whole file in, literally. The result is one long file per .cpp, called a translation unit.
  2. Compiler. Each translation unit is compiled separately into an object file (.o): machine code plus a table of the names (symbols) it defines and the ones it needs from elsewhere.
  3. Linker. Joins the object files and libraries into one executable, matching every needed symbol to exactly one definition.

The root page's token counter, split the way real projects are: a header (.h) declares the function (its name and types: a promise), a source file defines it (the body).

tokens.h
// tokens.h: the declaration (a promise that a definition exists somewhere)
#pragma once
#include <string_view>
int count_tokens(std::string_view text);
main.cpp
// main.cpp: uses count_tokens; only sees the declaration
#include "tokens.h"
#include <cstdio>

int main() {
    std::printf("%d tokens\n", count_tokens("C++ is fun, x86_64 too"));
}
tokens.cpp
// tokens.cpp: the definition
#include "tokens.h"
#include <cctype>

int count_tokens(std::string_view text) {
    int n = 0;
    bool inside = false;
    for (unsigned char c : text) {
        bool tok = std::isalnum(c) && c < 128;
        if (tok && !inside) n += 1;
        inside = tok;
    }
    return n;
}
What the preprocessor made of the 7-line main.cpp, and what one standard header costs alone (the recorded counts)
$ wc -l main.cpp tokens.h; clang++ -std=c++20 -E main.cpp | wc -l
for h in cstdio string_view vector string algorithm iostream; do printf "#include <%s> alone: " $h; printf "#include <$h>\\n" | clang++ -std=c++20 -x c++ -E - | wc -l | tr -d " "; done
       7 main.cpp
       4 tokens.h
      11 total
   55693
#include <cstdio> alone: 732
#include <string_view> alone: 55683
#include <vector> alone: 72835
#include <string> alone: 59542
#include <algorithm> alone: 54846
#include <iostream> alone: 93507

Fifty-five thousand lines, nearly all from <string_view>.

Every .cpp that includes a standard header recompiles that header from text, which is why C++ builds are slow and why C++20 added modules (section 4) to replace textual inclusion.

The real commands and output for this step

The pipeline, step by step

The same three files through the three stages, with the real line counts, sizes, symbol tables and messages (Apple clang 17, -std=c++20); bars are to scale by line count. Predict before you pick "Forgot tokens.o": which stage fails, the compiler or the linker?

  1. Three source files. A header that declares count_tokens, a .cpp that defines it, and main.cpp that calls it: 25 lines together.
  2. main.cpp's translation unit. The preprocessor pastes tokens.h, and through it the standard headers, into main.cpp: 55,693 lines for the compiler to read. The last lines are your code (the closed block under the pipeline shows them).
  3. tokens.cpp's translation unit. tokens.cpp becomes its own translation unit of 55,700 lines. The two are processed separately; neither sees the other.
  4. Two object files. Each translation unit compiles to an object file of machine code: main.o needs count_tokens and printf (U); tokens.o defines count_tokens (T). The compiler trusted the declaration in tokens.h.
  5. The link. The linker matches main.o's U count_tokens to tokens.o's T (now green), leaves printf to the dynamic system library, and writes the executable.
  6. It runs. "C++ is fun, x86_64 too" has 6 tokens under the root page's rule (C, is, fun, x86, 64, too).

Reading a symbol table (nm): T (green) is defined here, U (red) is used here and defined elsewhere. The linker must find exactly one T for each U: none is "Undefined symbols", two is "duplicate symbol". The compiler accepted main.cpp on the header's promise alone, so a missing definition is always the linker's error.

The one definition rule (ODR) says a function may be defined once in the whole program. A function body in a header included from two .cpp files gives each object file its own copy: "duplicate symbol" from ld on macOS (GNU ld says "multiple definition"). The fix is inline ("identical copies may appear; keep one") or only a declaration in the header. Functions defined inside a class body, templates and constexpr functions are implicitly inline, which is why headers full of them link fine.

Python bridge
A header is like a .pyi stub (types only) that every user pastes into their file. Python resolves names when the line runs; C++ resolves them at link time, so a missing or duplicated function is a build error, never a run-time NameError.

CMake: the build system

CMake is the de facto standard build description: you list targets (executables, libraries) and their properties, and CMake generates the commands for a build tool such as Ninja. A real project separates a library from the program that uses it:

CMakeLists.txt
cmake_minimum_required(VERSION 3.28)
project(tokcount LANGUAGES CXX)

# A library target: compiled once, linked into anything that needs it
add_library(tokens src/tokens.cpp)
target_include_directories(tokens PUBLIC src)      # users of tokens see src/
target_compile_features(tokens PUBLIC cxx_std_20)  # and get C++20
target_compile_options(tokens PRIVATE -Wall -Wextra)

add_executable(tokcount src/main.cpp)
target_link_libraries(tokcount PRIVATE tokens)     # brings the include dir and C++20 along

PUBLIC properties travel to every target that links the library; PRIVATE ones do not: the single most useful idea in CMake. In the generated commands, -Icmake2/src and -std=gnu++20 reached main.cpp; -Wall -Wextra did not. The library became a static library libtokens.a (an archive of object files, made by ar). The payoff of separate compilation is incremental builds: editing a .cpp recompiles one file, editing a header recompiles everything that includes it.

The recorded commands: compile, nm, both link errors, the inline fix, both CMake projects, the rebuilds (Apple clang 17, CMake 4.4.4, Ninja)

Names like count_tokens(std::__1::basic_string_view<...>) are C++'s mangled names decoded by nm -C: the parameter types are part of the symbol, which is how overloading works at link time. printf stays U after linking: it lives in libSystem, linked dynamically.

$ clang++ -std=c++20 -O2 -Wall -c tokens.cpp && clang++ -std=c++20 -O2 -Wall -c main.cpp && ls *.o
main.o
tokens.o
$ nm -C main.o; echo ---; nm -C tokens.o
                 U count_tokens(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
0000000000000000 T _main
                 U _printf
000000000000003c s l_.str
0000000000000047 s l_.str.1
0000000000000000 t ltmp0
000000000000003c s ltmp1
0000000000000060 s ltmp2
---
                 U __DefaultRuneLocale
0000000000000000 T count_tokens(std::__1::basic_string_view<char, std::__1::char_traits<char> >)
                 U ___maskrune
0000000000000000 t ltmp0
00000000000000a8 s ltmp1
$ clang++ main.o -o app
Undefined symbols for architecture arm64:
  "count_tokens(std::__1::basic_string_view<char, std::__1::char_traits<char>>)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture arm64
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
[exit code 1]
$ clang++ main.o tokens.o -o app && ./app
6 tokens
util.h
#pragma once
// A function DEFINED in a header, not marked inline
int twice(int x) { return 2 * x; }
b.cpp
#include "util.h"
int a();
int main() { return a() + twice(2) - 6; }
$ clang++ -std=c++20 -c a.cpp b.cpp && clang++ a.o b.o -o app
duplicate symbol 'twice(int)' in:
    odr/a.o
    odr/b.o
ld: 1 duplicate symbols
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
[exit code 1]
util_inline.h
#pragma once
// The fix: inline allows one identical definition per translation unit
inline int twice(int x) { return 2 * x; }
$ sed -i.bak "s/util.h/util_inline.h/" a.cpp b.cpp && clang++ -std=c++20 -c a.cpp b.cpp && clang++ a.o b.o -o app && ./app; echo "exit code $?"
exit code 0
CMakeLists.txt
cmake_minimum_required(VERSION 3.28)
project(hello LANGUAGES CXX)
add_executable(hello main.cpp)
$ cmake -S . -B build -G Ninja -DCMAKE_CXX_COMPILER=clang++ > /dev/null && cmake --build build && ./build/hello
[1/2] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[2/2] Linking CXX executable hello
hello from CMake
$ cmake -S . -B build -G Ninja && cmake --build build --verbose
clang++  -Icmake2/src -std=gnu++20 -arch arm64 -o CMakeFiles/tokcount.dir/src/main.cpp.o -c cmake2/src/main.cpp
clang++  -Icmake2/src -std=gnu++20 -arch arm64 -Wall -Wextra -o CMakeFiles/tokens.dir/src/tokens.cpp.o -c cmake2/src/tokens.cpp
cmake -E rm -f libtokens.a && ar qc libtokens.a  CMakeFiles/tokens.dir/src/tokens.cpp.o && ranlib libtokens.a && cmake -E touch libtokens.a
clang++ -arch arm64 -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/tokcount.dir/src/main.cpp.o -o tokcount  libtokens.a
$ ./build/tokcount
6 tokens
$ touch src/tokens.cpp && cmake --build build
[1/3] Building CXX object CMakeFiles/tokens.dir/src/tokens.cpp.o
[2/3] Linking CXX static library libtokens.a
[3/3] Linking CXX executable tokcount
$ touch src/tokens.h && cmake --build build
[1/4] Building CXX object CMakeFiles/tokcount.dir/src/main.cpp.o
[2/4] Building CXX object CMakeFiles/tokens.dir/src/tokens.cpp.o
[3/4] Linking CXX static library libtokens.a
[4/4] Linking CXX executable tokcount
$ cmake --build build
ninja: no work to do.

What it buys: each file compiles once, in parallel, and only what changed rebuilds. What it costs: headers are re-parsed in every file that includes them, and you maintain declarations and definitions separately. Common mistakes: a definition in a header without inline; global flags instead of per-target properties; forgetting -std= (section 4). llama.cpp's CMake build: the llama.cpp page, section 2.

2. Undefined behaviour

The C++ standard lists operations whose result it does not define: reading outside an array or freed memory, overflowing a signed integer, reading an uninitialised variable, two threads writing one variable without synchronisation, falling off the end of a function that returns a value, and others. Such a program has undefined behaviour (UB): not "a wrong answer" but no meaning at all. The compiler is allowed to assume UB never happens, and its optimiser uses that assumption to delete checks and simplify code. So a program with UB can work at -O0 and break at -O2, or work today and break after a compiler upgrade. This is the deepest difference from Python, where every one of these is either impossible or an exception.

The classic example: "will x + 1 overflow?" written the obvious way.

overflow.cpp
#include <climits>
#include <cstdio>

// "Will adding 1 overflow?" written the way you would in Python
__attribute__((noinline)) bool will_overflow(int x) {
    return x + 1 < x;   // signed overflow is UB, so the compiler may assume x + 1 > x
}

int main() {
    std::printf("will_overflow(INT_MAX) = %d\n", will_overflow(INT_MAX));
}
Predict, then reveal: compiled with -O2, what does will_overflow(INT_MAX) return? And at -O0?
$ clang++-23 -std=c++23 -O0 overflow.cpp -o overflow && ./overflow
will_overflow(INT_MAX) = 1
$ clang++-23 -std=c++23 -O2 overflow.cpp -o overflow && ./overflow
will_overflow(INT_MAX) = 0

At -O0 the addition wrapped around to a negative number and the test said 1. At -O2 the compiler reasoned "signed overflow cannot happen, so x + 1 < x is always false" and compiled the function to return false.

Neither build reported anything. The same assumption is what makes signed loop counters fast: a signed counter never overflows, so i + 1 > i and the loop's trip count can be computed without wrap-around checks, which enables vectorisation and widening it to 64 bits. Sanitizers are compiler modes that add run-time checks for UB; UndefinedBehaviorSanitizer (UBSan) catches this one:

$ clang++-23 -std=c++23 -O2 -fsanitize=undefined overflow.cpp -o overflow && ./overflow
overflow.cpp:6:14: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior overflow.cpp:6:14 
will_overflow(INT_MAX) = 1

(Under UBSan the program prints 1 again: the instrumented build computes the addition so it can check it.) The fix is to test before adding: x == INT_MAX, or __builtin_add_overflow, or C++26's <stdckdint.h> checked arithmetic. Unsigned integers do not have this problem: they wrap around by definition.

Each program was compiled with LLVM clang 23.1.2 without optimisation (-O0) and with it (-O2), and run; then with the tool that catches it: a sanitizer, a warning, or a hardened standard library. Every output is the real one. For each case, predict before you read the two runs: does the bug show at -O0, at -O2, or at neither? Notice how often a buggy program prints something plausible.

Commands as recorded by src/ca/steps/40_ub.sh; each run had a 5-second time limit. The uninitialised case printed "not seen" at -O0 and "seen" at -O2 for the same call, and the compiler warned only with -Wall.

Your defences

  1. Warnings: -Wall -Wextra always, -Werror in CI. They caught the uninitialised read, the dangling string_view and the missing return in the gallery.
  2. Sanitizers in tests: ASan (out of bounds, use after free, double free), UBSan (overflow, bad shifts, missing return), TSan (data races). They slow the program, so they run in tests, not production.
  3. A hardened standard library: libc++ can check v[i], front(), string_view bounds and more, turning silent UB into a trap.
  4. Initialise everything; C++26 turns reading an uninitialised local into erroneous behaviour, a defined (wrong) value the implementation may diagnose, instead of UB (P2795).
  5. Prefer what cannot be misused: .at(i) or a hardened library over raw indexing in non-hot code, smart pointers over new, values over references when lifetimes are unclear.
The defences in detail: flags, slowdowns, hardening modes (documentation checked 2026-10-05)
  • Flags: -fsanitize=address (ASan), -fsanitize=undefined (UBSan), -fsanitize=thread (TSan). Slowdown: about 2 times for ASan per its documentation, 5 to 15 times for TSan per its documentation.
  • On this Mac Apple's own ASan did not start (the root's Toolchain atlas records it); LLVM clang 23's worked, and every sanitizer report on this page is from it.
  • libc++ hardening: -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST is meant for production (cheap checks, a silent trap); the _DEBUG mode prints why (the "Index past the end" case shows both).
  • -ftrivial-auto-var-init=zero made the uninitialised example print "not seen" at -O2.
The honest summary
No tool catches all UB, and sanitizers find only what your tests execute. C++ makes you responsible for memory safety; Rust moves most of this list into compile errors (Rust: the essentials, and the root page's comparison).

3. Libraries: header-only, static, dynamic, and getting them

Python has pip install and wheels. C++ has no official package manager, and the reason is technical: a compiled C++ library works with your program only if it was built with a compatible compiler, standard library and flags (the same ABI, application binary interface; the machine page, section 11). A mismatch gives link errors or, worse, silent memory corruption. So shipping prebuilt binaries is much harder than in Python, and the historical answer was "build it yourself" or "copy the source in". Three ways a library reaches your program:

  • Header-only: the whole library is headers (all inline functions and templates), so there is nothing to build or link: nlohmann/json, Catch2, Eigen. It sidesteps packaging and ABI, and costs compile time in every file that includes it.
  • Static library (.a, .lib): object files copied into your executable at link time, like libtokens.a in section 1. One self-contained binary; every program carries its own copy.
  • Dynamic (shared) library (.dylib, .so, .dll): loaded when the program starts. Smaller binaries and shared updates, but the library must be present, at a compatible version, on the machine that runs it. Even the small program from section 1 depends on two, libc++ and libSystem:
$ otool -L app
app:
	/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 2000.63.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1356.0.0)

Getting dependencies, oldest to newest: system packages, vendoring the source (llama.cpp does), CMake FetchContent, then the package managers vcpkg and Conan. The build system (CMake) and the package manager are separate tools, and there is no lock-file culture like uv.lock: pin versions and record the toolchain. Two files compiled with different flags that see different definitions of the same thing break the one definition rule, silently.

The five ways to get a dependency, compared (the root's Toolchain atlas tab compares the four languages' tools)
ApproachHowGood forCost
System packagesbrew install, apt install libfoo-dev, found with find_package or pkg-configQuick local workWhatever version the system ships; not reproducible
Vendoring, git submodulesCopy the source into your repoTotal control; very common: llama.cpp's vendor/ folder holds nlohmann/json, cpp-httplib, stb and miniaudio at the pinned commitManual updates
CMake FetchContentName a git URL and tag in CMakeLists.txt; built with your projectA handful of dependenciesNo lock file, no binary cache
vcpkg (Microsoft)vcpkg.json manifest; builds from source with binary caching; a CMake toolchain fileNew CMake projectsAnother tool to learn
Conan (JFrog)Binary packages described by profiles (compiler, standard library, architecture, build type)Enterprises, CI-heavy setupsHeavier

The root page is Topic: programming-languages (its Toolchain atlas tab). For Python bindings of C++ code, its Benchmark tab covers pybind11 and nanobind.

Fig. 3 · Three ways a library reaches your program: pasted into every file, copied in at link time, or loaded when the program starts
Header-only (nlohmann/json, Catch2, Eigen)
json.hpp a.cpp + json.hpp b.cpp + json.hpp pasted by #include compiled again in every file; nothing to link
Static library (libtokens.a, section 1)
libtokens.a tokens.o copied inat link app main.o tokens.o one self-contained binary; each program its own copy
Dynamic library (otool -L app, below)
app libc++.1.dylib libSystem.B.dylib found in /usr/lib and loaded when the program starts

Header-only trades build time for no packaging; static trades binary size for no run-time dependencies; dynamic shares one copy but needs a compatible version on every machine that runs it.

4. Which standard: ask for one, always

C++ is standardised by an ISO committee (WG21) on a three-year train: C++11, 14, 17, 20, 23, 26. Nothing old is removed, so "modern C++" is a subset you choose to write, the one these pages teach. Each compiler and standard library implements each standard gradually, and the two can differ: a feature needs both. The default language version differs between compilers and even versions of one compiler; measured here, Apple clang 17 defaults to C++14 and Apple clang 14 to C++98. So pass -std=c++20 or newer, or in CMake target_compile_features(t PUBLIC cxx_std_20). Write C++20 as the baseline and use C++23 where your compilers report it; C++26 is finished on paper and mostly not shipped.

Where C++20, C++23 and C++26 stand, October 2026 (dated; checked 2026-10-05; feature macros measured on this machine)
$ for c in /usr/bin/clang++ clang++ clang++-23; do printf "%-18s default __cplusplus = " $c; echo __cplusplus | $c -x c++ -E -P - | tail -n 1; done
/usr/bin/clang++   default __cplusplus = 199711L
clang++            default __cplusplus = 201402L
clang++-23         default __cplusplus = 201703L

(199711L is C++98, 201402L C++14, 201703L C++17.) Elsewhere: GCC 16 (released 2026-04-30) is the first major compiler to default to C++20 (GCC 16 changes); upstream Clang has defaulted to C++17 since Clang 16 (Clang status); MSVC still defaults to C++14 (/std).

The standard way to ask a toolchain what it supports is the feature-test macros in <version>. This program prints them; "-" means not defined:

$ clang++ -std=c++26 features.cpp -o features17 && ./features17
__cplusplus                    202400L
__cpp_concepts                 202002
__cpp_lib_ranges               202406L
__cpp_lib_span                 202002L
__cpp_lib_format               202110L
__cpp_impl_coroutine           201902L
__cpp_lib_jthread              201911L
__cpp_lib_expected             202211L
__cpp_lib_print                202207L
__cpp_lib_mdspan               202406L
__cpp_lib_ranges_to_container  202202L
__cpp_lib_generator            -
__cpp_lib_flat_map             202207L
__cpp_lib_stacktrace           -
__cpp_explicit_this_parameter  -
__cpp_lib_modules              202207L
__cpp_contracts                -
__cpp_impl_reflection          -
__cpp_lib_simd                 -
__cpp_lib_senders              -
__cpp_pack_indexing            202311L
$ clang++-23 -std=c++26 features.cpp -o features23 && ./features23
__cplusplus                    202400L
__cpp_concepts                 202002
__cpp_lib_ranges               202406L
__cpp_lib_span                 202002L
__cpp_lib_format               202110L
__cpp_impl_coroutine           201902L
__cpp_lib_jthread              201911L
__cpp_lib_expected             202211L
__cpp_lib_print                202207L
__cpp_lib_mdspan               202406L
__cpp_lib_ranges_to_container  202202L
__cpp_lib_generator            -
__cpp_lib_flat_map             202511L
__cpp_lib_stacktrace           -
__cpp_explicit_this_parameter  202110L
__cpp_lib_modules              202207L
__cpp_contracts                -
__cpp_impl_reflection          -
__cpp_lib_simd                 -
__cpp_lib_senders              -
__cpp_pack_indexing            202311L
StandardWhat matters for youStatus here (Apple clang 17 / LLVM clang 23)
C++20 (the baseline to write)Concepts, ranges, std::span, std::format, <=>, coroutines (language machinery only), std::jthread, modulesAll reported by both, modules aside (see below)
C++23 (usable now)std::expected, std::print, ranges::to, std::mdspan (a multidimensional view over a flat buffer: the standard way to pass a tensor), std::flat_map, deducing this, import std;, std::generator, std::stacktraceMost reported by both; std::generator and std::stacktrace by neither; deducing this only by clang 23
C++26 (technical work finished 2026-03-28)Static reflection (P2996: code that inspects types at compile time, e.g. enum-to-string and bindings without macros), contracts (P2900: pre, post, contract_assert), std::execution (P2300: a standard model for asynchronous and parallel work), a hardened standard library (P3471), erroneous behaviour for uninitialised reads (P2795), std::simd, std::inplace_vector, std::hive, <linalg>Reflection, contracts, std::execution and std::simd reported by neither; Clang's status page lists reflection, contracts and P2795 as "No". GCC 16 implements reflection (behind -freflection), contracts and P2795

Sources: Sutter's trip report, "C++26 is done" (reflection, contracts, std::execution, hardening, erroneous behaviour); cppreference's C++26 page (paper numbers, the other library additions); GCC 16 changes and Clang's C++ status (compiler support). For any feature, cppreference's compiler support tables are the place to check.

Modules replace textual #include with compiled interfaces (import std;), attacking the 55,000-line problem of section 1. The language feature is in C++20 and import std in C++23, but tooling still lags: GCC 16's notes say modules support "is still experimental and must be enabled by -fmodules", and CMake supports named modules since 3.28 but import std only behind an experimental gate (cmake-cxxmodules). Headers remain the pragmatic default in 2026; llama.cpp uses them.

Corrections to the old "C++: modern practice and standards status" page
  • "C++26 was finalized in March 2026": the technical work finished on 2026-03-28 in London (Croydon); then comes the international ballot (DIS) and ISO publication, which was not confirmed as of 2026-10-05.
  • "C++20 is the production baseline nearly everywhere": as a target, yes; as a default, no. Only GCC 16 defaults to C++20; Clang defaults to C++17, MSVC to C++14, and Apple clang 17 here to C++14 (measured above).
  • "MSVC completes /std:c++23 with Build Tools 14.52": not yet true. The current release is 14.51 in Visual Studio 2026 18.10.3 (2026-09-29) and Microsoft's documentation still lists /std:c++23preview (root page, Toolchain atlas corrections).
  • "Pattern matching did NOT make it": confirmed in the sense that cppreference's C++26 feature list has no pattern matching.
  • The old list of C++26 features is otherwise right; this page adds hardening and erroneous behaviour, the two that change day-to-day safety.

5. Mistakes that catch experienced people, and a hygiene checklist

Each of these compiles. Most are lifetime bugs: a second owner, or a reference that outlives its owner.

MistakeWhat actually happensShown on
A string_view, span or range view that outlives its ownerViews do not own; one made from a temporary dangles at the semicolonGallery
A reference, pointer or iterator into a vector, kept across push_backGrowth reallocates and frees the old buffer. Use indices, or reserve firstGallery; Classes, section 4
A lambda that captures a local by reference and outlives itIt reads a dead stack slot, often plausiblyGallery; Classes, section 5
A destructor that frees, with the compiler-written copy left in placeTwo objects own one buffer and both free it: a double freeGallery; Ownership, section 7
Using an object after std::moveValid but unspecified. Assign to it or let it dieOwnership, section 5
shared_ptr by reflexCycles leak; atomic counting slows every copy; ownership becomes unclear. unique_ptr firstOwnership, section 4 (measured)
Slicing a derived object into a base by value; a public non-virtual destructor in a base used through pointersThe derived part is dropped, or never destroyed. Pass polymorphic objects by reference or pointerClasses, section 2
Static initialisation order across filesGlobals in different .cpp files are initialised in an unspecified orderBelow
Unsigned arithmetic going below zero0 - 1 wraps to 18,446,744,073,709,551,615Below
Treating a data race as "sometimes a wrong value"It is UB: the race printed 1098717 instead of 2000000 at -O0 and the right answer at -O2, so a test at -O2 passesGallery; Machine, section 8
Four of these in detail (range-for temporaries, static order, unsigned loops, the race)
  • Range-for over a member of a temporary, for (auto& x : make().items()), dangled until C++23 extended the lifetime of every temporary in the range-for initializer (P2718); the same expression outside a range-for still dangles, so the old page's "fixed for some cases in C++23, not all" stands.
  • Static initialisation order: one global's constructor that uses another global from a different file may see it unconstructed. Use a function returning a reference to a function-local static, which is initialised on first use.
  • for (size_t i = v.size() - 1; i >= 0; --i): size_t is unsigned, so i >= 0 is always true; an empty vector makes even the first value huge. Mixing signed and unsigned in a comparison converts the signed side to unsigned (clang warns with -Wextra).
  • The race: the optimiser turned each thread's loop into one addition, which hid the lost updates. Use std::atomic or a mutex.

Hygiene checklist

  • RAII everywhere; no naked new/delete; unique_ptr by default.
  • Rule of zero: hold members that clean up after themselves (std::vector, std::string, unique_ptr) and write no special member at all; if you must write one, write all five, with noexcept moves.
  • Parameters: string_view and span<const T> to read; never store them past the call without thought.
  • const by default; constexpr where a value can be computed at compile time.
  • auto for iterators, lambdas and long type names; concrete types at API boundaries.
  • Build with -std=c++20 or newer and -Wall -Wextra (-Werror in CI); ASan, UBSan and TSan in CI test runs; clang-format and clang-tidy; CMake targets with PUBLIC/PRIVATE properties, presets, and vcpkg or Conan.

6. The child pages

Each stands alone and assumes only this page; the order below is the one the ideas build in. Times are each child's own header (230 words a minute), with the closed blocks counted apart; each card names the child's 3D figures, which Fig. 1 links step by step.

C++: ownership, moves and object lifetimes

Child page, about 21 min, plus 13 in closed details.

Every object has exactly one lifetime, and RAII plus moves let ownership, not a garbage collector, decide when it ends. Replayed from real constructor and destructor logs. Figures: the stack and heap of one run, a copy and a move; owners and reference counts.

C++: classes, templates and the standard library

Child page, about 25 min, plus 17 in closed details.

Abstractions are resolved at compile time unless you ask for run-time dispatch, and the costs are measured: virtual calls, templates, the standard library, lambdas, exceptions against std::expected. Figures: a virtual call followed through memory; a vector's size against its capacity.

C++: the machine underneath: caches, layout, SIMD and the memory model

Child page, about 33 min, plus 21 in closed details.

Memory, not arithmetic, sets the speed; caches, layout and SIMD decide it. Caches, layout, assembly, SIMD, branches, atomics and the ABI, all measured on an M1 Pro. Figures: the cache ladder, AoS against SoA, SIMD schedules, message passing, false sharing.

C++: reading llama.cpp, one token through the code

Child page, about 37 min, plus 39 in closed details.

One token is a ggml graph built, planned and run by threads over repacked quantised blocks, traced through the code and timed end to end. Figures: one decoded token, layer 0 of the real graph, one quantised block, the KV cache.

Elsewhere: the same program in Python, C++, Rust and TypeScript, and the benchmark across them, is Topic: programming-languages. The sibling language pages are Python: the essentials, Rust: the essentials and JavaScript and TypeScript: the essentials. Kernels and CUDA C++ are in Topic: cuda-and-gpu-programming; the KV cache, batching and serving in Topic: inference-and-serving.

Every output was produced by src/ca/run_all.sh on an Apple M1 Pro under macOS 27: the build and the gallery on 2026-10-05 (Apple clang 17.0.0 with the macOS 26 SDK; LLVM clang 23.1.2 for the gallery and sanitizers; CMake 4.4.4 with Ninja), the hero on 2026-10-26 (Apple clang 17, CPython 3.14.8). This page replaces the old written pages "C++: zero to expert" and "C++: modern practice and standards status"; every claim from them was checked, with corrections in boxes on the page that owns each subject. Rebuilt on 2026-10-26 as the essentials page of four children.