Skip to content

Build basics: compilers, CMake, warnings, sanitizers

Difficulty: Beginner

Key concepts

  • compiling
  • linking
  • translation unit
  • header file
  • source file
  • one definition rule
  • CMake
  • target
  • compiler warnings
  • sanitizers
  • The steps between your .cpp files and a running program, and which step each kind of error comes from.
  • What belongs in a header, and what belongs in a source file.
  • How to read a minimal CMakeLists.txt that builds a library, a program, and a test.
  • Why this site treats compiler warnings as errors.
  • What the three sanitizers find, and what they cannot find.

A design is split into parts: a library with a small public interface, the code that uses it, the tests that check it. The build is where that split becomes real. Headers are the parts’ published interfaces, the linker checks that every function that is actually used has exactly one definition, and the build files say which part may use which. Some “mysterious” errors are a design boundary drawn slightly wrong, and they are easy to fix once you know which step reported them.

The example: a fines library and a program

Section titled “The example: a fines library and a program”

The example is as small as possible: a library with two functions, a program that uses it, and a test. It has a header, fines.hpp:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

fines.hpp
// CPP-15 example: the library's header. It declares what other files may
// use; the definitions are in fines.cpp. A declaration ends in `;` instead of
// a body: it tells the compiler the function's name, parameters, and return
// type, which is all a caller needs in order to be compiled.
//
// Ownership: plain functions on values. Thread safety: pure functions.
#pragma once
#include <string>
namespace lld::build {
// Late fee in cents: 25 cents per day late. Returns 0 if days_late <= 0.
// Precondition: days_late <= 85'899'345; a larger value overflows int.
// (85'899'345 * 25 = 2'147'483'625, just under the largest int on this
// site's compilers, 2'147'483'647. The ' marks only separate the digits.)
[[nodiscard]] int late_fee_cents(int days_late);
// Formats cents as dollars, for example 125 -> "$1.25".
// Meant for cents >= 0, which is all late_fee_cents returns.
[[nodiscard]] std::string format_cents(int cents);
} // namespace lld::build

a source file that defines what the header declares, fines.cpp:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

fines.cpp
// CPP-15 example: the library's source file, compiled once into fines.o
// and then into the static library.
//
// Ownership and thread safety: see fines.hpp.
#include "fines.hpp"
#include <cstdio>
namespace lld::build {
// An unnamed namespace: what is declared inside it belongs to this file
// only. Other files cannot use cents_per_day, and could reuse the name.
namespace {
constexpr int cents_per_day = 25; // internal: not visible to other files
} // namespace
// The definition that fines.hpp's declaration promised. `?:` reads "if
// days_late > 0, then days_late * 25, otherwise 0": no fee for being on time.
int late_fee_cents(int days_late) { return days_late > 0 ? days_late * cents_per_day : 0; }
// Splits cents into whole dollars and the cents left over, then writes them
// as text: 125 / 100 is 1 (integer division drops the fraction) and
// 125 % 100 is 25 (the remainder), giving "$1.25".
std::string format_cents(int cents) {
// A fixed buffer of 32 characters on the stack, plenty for any int pair.
char text[32];
// std::snprintf writes formatted text into the buffer, never more than
// `sizeof text` characters including the final '\0' that ends the text.
// %d prints an int; %02d prints it with at least 2 digits, padding with a
// zero, so 5 cents prints as "05" and 305 becomes "$3.05", not "$3.5".
// For a negative amount the output would be wrong ("$-1.-25" for -125),
// which is why the header says it is meant for cents >= 0.
std::snprintf(text, sizeof text, "$%d.%02d", cents / 100, cents % 100);
// Returning the char array builds a std::string from it: the characters
// are copied, so the result is still valid after `text` disappears.
return text;
}
} // namespace lld::build

and a program that uses the library through the header, main.cpp:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// CPP-15 example: a program that uses the library through its header.
//
// Ownership: values only. Thread safety: single-threaded.
#include "fines.hpp"
#include <iostream>
int main() {
// Loops over the three values in the brace list. The functions are
// called by their full names, namespace included: lld::build::format_cents.
// For 3 days: late_fee_cents(3) is 75, and format_cents(75) is "$0.75".
for (const int days : {0, 3, 12}) {
std::cout << days << " days late: "
<< lld::build::format_cents(lld::build::late_fee_cents(days)) << '\n';
}
}
Expected output
0 days late: $0.00
3 days late: $0.75
12 days late: $3.00

Building happens in separate steps, and each .cpp file goes through the first steps on its own.

  1. Preprocessing. Each #include is replaced by the contents of the included file. The result, one .cpp file with everything it includes, is called a translation unit. main.cpp and fines.cpp are two separate translation units, and both contain a copy of fines.hpp.
  2. Compiling. The compiler turns each translation unit into an object file (main.o, fines.o) of machine code. It checks syntax and types, but it sees only one translation unit at a time. While compiling main.cpp, it knows from the header that late_fee_cents(int) exists and returns int. It does not know, and does not need to know, how it works. It leaves a note: “this object file needs late_fee_cents(int) from somewhere”.
  3. Archiving (for a static library). fines.o is packed into a library file, libbuild_fines.a, so other programs can link it.
  4. Linking. The linker combines the object files and libraries into one program. It matches every “needs” note with exactly one definition. If one is missing, or there are two, this step fails.
Each .cpp file is preprocessed and compiled on its own; the linker joins the results
Text description of the diagram

The header fines.hpp holds the declarations and is included by both main.cpp and fines.cpp. Each source file is preprocessed and compiled on its own. main.cpp becomes main.o, which needs late_fee_cents and format_cents. fines.cpp becomes fines.o, which defines them. fines.o is archived into the static library libbuild_fines.a. The linker then takes main.o and the library and joins them into the program build_fines_report, matching each needed function with its definition.

Diagram source (Mermaid)
flowchart LR
H["fines.hpp (declarations)"]
H -.->|"#include"| M["main.cpp"]
H -.->|"#include"| F["fines.cpp"]
M -->|"preprocess and compile"| MO["main.o: needs late_fee_cents, format_cents"]
F -->|"preprocess and compile"| FO["fines.o: defines late_fee_cents, format_cents"]
FO -->|"archive"| A["libbuild_fines.a"]
MO --> L{"link"}
A --> L
L --> P["build_fines_report (the program)"]

Done by hand, with GCC, the steps are four commands (CMake runs equivalent ones for you; these were run on the site’s build machine):

Terminal window
g++ -std=c++20 -Wall -Wextra -Wpedantic -Werror -c fines.cpp -o fines.o
g++ -std=c++20 -c main.cpp -o main.o
ar rcs libfines.a fines.o
g++ main.o libfines.a -o report

-c means “compile only, do not link”. The last command links. These commands name the library libfines.a; CMake, below, names it libbuild_fines.a, after its target build_fines.

Knowing the steps tells you who reported an error:

  • A compiler error names a source file and line: a syntax error, a type mismatch, an undeclared name. It is about one translation unit.
  • A linker error usually names an object file and a symbol (a function or variable), with words like “undefined reference” or “multiple definition”. It is about how the translation units fit together.

A declaration says that something exists and what its type is: int late_fee_cents(int days_late);. A definition provides it: the function’s body, or the storage for a variable. The basic rule is:

  • A header contains declarations that other files need: the part’s public interface. Every file that includes it gets the same declarations.
  • A source file contains definitions, compiled once.

The rule behind it is the one definition rule (ODR): an ordinary function or variable used by the program must be defined exactly once in the whole program. A definition in a header would be compiled into every translation unit that includes it, and the linker would find several. Here is a real message from this machine, for a non-inline function twice defined in a header included by two files:

multiple definition of `twice(int)'; …a.cpp:(.text+0x0): first defined here

Some definitions are allowed in headers, and normally live there: class definitions, inline functions (including member functions defined inside the class), constexpr functions, and templates. For these, the compiler needs to see the definition in every file that uses them, and the ODR permits one identical copy per translation unit.

Two details of fines.cpp show what is not part of the interface:

  • cents_per_day is inside an unnamed namespace. Everything declared in one has internal linkage: it is visible only in fines.cpp, and another file could use the same name without a clash. (A constexpr variable at namespace scope already has internal linkage, so for this constant the unnamed namespace only makes the intent explicit. For helper functions and classes, it is what keeps them private to the file.)
  • <cstdio> is included in fines.cpp, not in the header, because only the implementation uses it. Every include in a header is passed on to every file that includes it, so headers should include only what their declarations need. fines.hpp includes <string> because format_cents returns a std::string.

#pragma once stops a header’s contents from appearing twice in one translation unit when it is included by two routes. It is not in the C++ standard, but GCC, Clang, and MSVC support it. The standard alternative is an #ifndef include guard.

Typing commands does not scale past a few files. CMake reads a description of what to build and generates the commands. This is the example’s whole CMakeLists.txt:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

CMakeLists.txt
# The oldest CMake version this file is written for. Older versions refuse
# to run it rather than misreading it.
cmake_minimum_required(VERSION 3.21)
# The project's name, and the one language it uses: C++ (CXX).
project(fines LANGUAGES CXX)
# A library made from fines.cpp. Anything that links to it gets its include
# directory and needs C++20.
# STATIC: the library's code is copied into each program that links it.
add_library(build_fines STATIC fines.cpp)
# Where fines.hpp is: this directory. PUBLIC passes the setting on to every
# target that links build_fines, so main.cpp finds the header too.
target_include_directories(build_fines PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
# Compile with C++20, and require it of every user too (PUBLIC).
target_compile_features(build_fines PUBLIC cxx_std_20)
# Warnings on, and every warning an error. PRIVATE: for this target only.
target_compile_options(build_fines PRIVATE -Wall -Wextra -Wpedantic -Werror)
# A program that uses the library.
# A program named build_fines_report, made from main.cpp.
add_executable(build_fines_report main.cpp)
# Link it with the library. This also hands it the library's PUBLIC settings:
# the include directory and C++20.
target_link_libraries(build_fines_report PRIVATE build_fines)
target_compile_options(build_fines_report PRIVATE -Wall -Wextra -Wpedantic -Werror)
# A test, run by `ctest`.
# enable_testing() turns on CTest for this directory. The test is an ordinary
# program; add_test registers it under a name, and it passes if it exits
# with status 0.
enable_testing()
add_executable(build_fines_check check_fines.cpp)
target_link_libraries(build_fines_check PRIVATE build_fines)
target_compile_options(build_fines_check PRIVATE -Wall -Wextra -Wpedantic -Werror)
add_test(NAME build_fines_check COMMAND build_fines_check)

CMake thinks in targets: a library, a program, or a test, each with its own sources and settings.

  • add_library(build_fines STATIC fines.cpp) defines a static library target.
  • target_include_directories(build_fines PUBLIC …) says where its header is. PUBLIC means “this target needs it, and so does anything that links to it”, so main.cpp can write #include "fines.hpp" without its own setting.
  • target_compile_features(build_fines PUBLIC cxx_std_20) requires C++20 for the library and for its users.
  • target_compile_options(… PRIVATE -Wall …) turns on warnings. PRIVATE means “only for this target”: the library’s warning choices are not forced on the programs that use it.
  • add_executable and target_link_libraries(… PRIVATE build_fines) define the program and link it with the library. Linking a target also gives you its PUBLIC settings.
  • enable_testing() and add_test register a test that ctest can run. A test passes when its program exits with status 0. check_fines.cpp is the smallest possible test; the testing lesson replaces it with a small test harness.

PUBLIC and PRIVATE are design tools: they make a part’s dependencies and interface explicit, in the same way public and private do in a class.

To build and test the example on its own, from its directory:

Terminal window
cmake -S . -B out
cmake --build out
ctest --test-dir out

-S is the source directory and -B is the build directory. Keeping build files out of the source tree means one source tree can have several builds, for example one per compiler, and deleting the build directory always gives a clean start. (On the site’s build machine, the example was built and tested this way, and its test passed.)

The site’s own examples are built together, with a top-level CMakeLists.txt that includes each example, and with presets in CMakePresets.json, one per compiler and sanitizer configuration: cmake --preset gcc-debug, then cmake --build --preset gcc-debug. The reading-examples lesson lists them.

A compiler warning means the code is valid C++ but probably not what you meant. This site compiles every example with:

  • -Wall -Wextra: a broad set of useful warnings (despite the name, -Wall is not “all”).
  • -Wpedantic: warn about compiler extensions that are not standard C++.
  • -Werror: treat every warning as an error, so the build fails.

These are the GCC and Clang spellings. Microsoft’s compiler has its own, such as /W4 for more warnings and /WX for warnings as errors.

The reason for -Werror is practical. Warnings that do not fail the build pile up. Once there are fifty, nobody reads the fifty-first, and it is the one that mattered. With -Werror, the count stays at zero.

Warnings do not catch everything. In one experiment on this machine, the definition in fines.cpp was changed by mistake to late_fee_cents(long). With the site’s flags, fines.cpp still compiled without a warning: the compiler saw a perfectly valid, new function. The mistake only appeared when linking, as undefined reference to 'lld::build::late_fee_cents(int)'. GCC’s -Wmissing-declarations would have caught it while compiling fines.cpp:

warning: no previous declaration for ‘int lld::build::late_fee_cents(long int)’ [-Wmissing-declarations]

That warning is not part of -Wall or -Wextra. Code bases often add more warnings than this site does. Choose a set, and keep it at zero.

Many serious bugs cannot be seen by the compiler, because they depend on what happens while the program runs. They lead to undefined behaviour: the program may print a wrong value, crash, or appear to work. Sanitizers are compiler options that add checks to the program, so that such a bug stops it with a report instead of continuing silently.

Sanitizer Flag Finds
AddressSanitizer (ASan) -fsanitize=address Use after free, reading or writing outside an array or allocation, some leaks
UndefinedBehaviorSanitizer (UBSan) -fsanitize=undefined Signed integer overflow, invalid shifts, misaligned or null pointer use, and more
ThreadSanitizer (TSan) -fsanitize=thread Data races: two threads using the same memory unsynchronised, at least one writing

ASan and UBSan can be used together, as this site’s asan-ubsan preset does. TSan cannot be combined with ASan, so it has its own build. Sanitized programs run more slowly and use more memory, so they are used for tests and debugging, not usually for the shipped program.

The example’s late_fee_cents multiplies days_late by 25. A test program on this machine called it with the largest int. Built normally with GCC, it printed 2147483623, a plausible-looking but meaningless number, and exited successfully. Built with -fsanitize=undefined, Clang reported:

fines.cpp:15:70: runtime error: signed integer overflow: 2147483647 * 25 cannot be represented in type 'int'

Signed overflow is undefined behaviour in C++; the wrong number was just what happened on this machine. The example’s header now states the limit as a precondition. The testing lesson’s fee calculation shows another fix: compare with the limit before multiplying, so the overflow cannot happen.

Note what that run needed: a test that used an extreme input. A sanitizer checks only the code that actually runs, with the inputs it actually gets.

The containers lesson shows a reference into a std::vector that dangles after push_back reallocates. On this machine, built with -fsanitize=address by both GCC and Clang, the original version, which prints first.name with std::cout <<, ran without any report and exited with status 0. A version that instead called first.name.size() was stopped at once, with AddressSanitizer: heap-use-after-free, pointing at the line in main.

The most likely explanation, which was not confirmed further, is this. ASan mainly checks memory accesses in code compiled with -fsanitize=address, plus some C library functions, such as memcpy, that it replaces with checked versions. Printing a string is done inside the C++ standard library, which was compiled beforehand without ASan, so the bad read probably happened where ASan was not looking. size() is a small inline function, so its read was compiled into the example and checked. The lesson is the important part: a clean sanitizer run does not prove there is no bug. Sanitizers find many bugs cheaply, and are worth running on every test. Correct design, such as not keeping references across container changes, is still the real protection.

  • Defining a non-inline function or a global variable in a header. It causes “multiple definition” when two files include it.
  • Declaring a function and forgetting to define it, or linking without the library that defines it. It causes “undefined reference”.
  • A definition whose signature differs from its declaration. It compiles, but the declared function is still undefined.
  • Including more than needed in headers. Every user then depends on, and recompiles for, things it never uses.
  • Building in the source directory. Keep a separate build directory per configuration.
  • Ignoring warnings “for now”. Keep the count at zero.
  • Treating a clean sanitizer run as proof. It only covers the code and inputs that ran.

New requirement: “The fines code is also needed by the overnight billing program.”

Because the fines code is already its own library target, the billing program needs only its own add_executable and one link line: target_link_libraries(billing PRIVATE build_fines). It gets the header path and the C++20 requirement through the PUBLIC settings, and the library is compiled once. If the fee rules had been written inside main.cpp, they would now have to be moved out, or copied, which is how two programs end up charging different fees. Drawing the boundary in the build is drawing it in the design.

Exercise: Diagnose a link error

A teammate gets this when building the report program. The messages are real, from this machine:

/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0xb6): undefined reference to `lld::build::late_fee_cents(int)'
/usr/bin/ld: main.cpp:(.text+0xc6): undefined reference to `lld::build::format_cents[abi:cxx11](int)'
collect2: error: ld returned 1 exit status
  1. Did this come from the compiler or the linker? How can you tell?
  2. Give two different causes that produce exactly these messages.
  3. Another time, the teammate sees only the first line, for late_fee_cents, and not the one for format_cents. What is the most likely cause?
Show the explained answer
  1. The linker. /usr/bin/ld is the linker (and collect2 is GCC’s helper that runs it), the location is an object file section (.text+0xb6) rather than a source line, and “undefined reference” means a compiled call has no matching definition. main.cpp itself compiled: the header declared both functions. ([abi:cxx11] is a tag that GCC’s standard library adds to functions returning std::string. It is part of the symbol’s name, not a separate problem.)
  2. Both functions are missing, so the whole definition file is not in the program. For example, fines.cpp was not compiled into the library, or the program was linked without the library: target_link_libraries was missing, or the command line had main.o but not libfines.a. (On this machine, linking main.o alone produced exactly these lines.)
  3. Only late_fee_cents(int) is missing, while format_cents from the same file is found, so the library is linked. Most likely, the definition does not match the declaration: for example, fines.cpp defines late_fee_cents(long), a different function. On this machine, that mistake compiled without warnings under -Wall -Wextra and produced this exact link error. -Wmissing-declarations would have reported it when compiling fines.cpp. Other possible causes are a definition outside the namespace lld::build, or one hidden in an unnamed namespace.
  • Each .cpp file is preprocessed and compiled on its own into an object file; the linker joins them, and reports missing or duplicate definitions.
  • Headers hold declarations that other files need; source files hold definitions. Classes, inline functions, and templates are the exceptions that live in headers.
  • CMake describes targets. PUBLIC settings pass to users of a target and PRIVATE settings do not, which makes dependencies part of the design.
  • Treat warnings as errors and keep their count at zero, but know that some mistakes still compile.
  • ASan, UBSan, and TSan turn many kinds of undefined behaviour into clear reports, but only for the code and inputs that actually run.