Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Install a compiler
    4. Linux (Ubuntu or Debian)
    5. macOS
    6. Windows
    7. The flags this course uses
    8. Warnings, and making them errors
    9. Sanitizers: catching bugs while the program runs
    10. A number too big for its type
    11. Reading past the end of an array
    12. A minimal CMake project
    13. The Run button on this site
    14. Which one should I use?
    15. Under the hood
    16. Common pitfalls
    17. Forgetting -std=c++23
    18. A function that forgets to return
    19. Try it yourself

    Module 0 · Getting started

    0.2Setting up: compilers, warnings and sanitizers

    Install GCC or Clang, turn on the warnings and sanitizers this course uses so the compiler and the running program catch your mistakes, build with CMake, and see what the Run button does.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. Install a compiler
    4. Linux (Ubuntu or Debian)
    5. macOS
    6. Windows
    7. The flags this course uses
    8. Warnings, and making them errors
    9. Sanitizers: catching bugs while the program runs
    10. A number too big for its type
    11. Reading past the end of an array
    12. A minimal CMake project
    13. The Run button on this site
    14. Which one should I use?
    15. Under the hood
    16. Common pitfalls
    17. Forgetting -std=c++23
    18. A function that forgets to return
    19. Try it yourself

    Key terms

    GCC
    The GNU Compiler Collection, a free compiler. Its C++ compiler is the command g++.
    Clang
    Another free compiler, from the LLVM project. Its C++ compiler is the command clang++, and it takes the same flags as g++ for everything in this course.
    package manager
    A tool that installs software for you, such as apt on Ubuntu or Homebrew (brew) on macOS.
    WSL
    Windows Subsystem for Linux: a real Linux, such as Ubuntu, running inside Windows.
    flag
    An option you give a command, starting with -, such as -Wall.
    warning
    A message about code that compiles but is probably a mistake. On its own, a warning doesn't stop the build.
    -Werror
    A flag that turns every warning into an error, so the build fails until you fix it.
    unsigned int
    A whole number that can't be negative.
    undefined behavior
    Code the C++ rules give no meaning to. The compiler doesn't have to catch it, and the program might crash, print garbage or seem to work.
    sanitizer
    A checker the compiler builds into your program. It watches the program as it runs, and stops it with a report when it finds a bug.
    AddressSanitizer (ASan)
    The sanitizer for memory mistakes, such as using memory after it's freed. It includes LeakSanitizer, which reports memory that's never freed.
    UndefinedBehaviorSanitizer (UBSan)
    The sanitizer for broken rules such as a number too big for its type, or an array index past the end.
    array
    A fixed number of values of one type, side by side in memory. int readings[3] holds three ints, at indexes 0, 1 and 2.
    CMake
    A tool that writes the build commands for you, from a short description of your project in a file called CMakeLists.txt.
    build type
    A CMake setting that picks a group of flags: Debug for finding bugs, Release for a fast program to ship.
    Compiler Explorer
    A website, godbolt.org, that compiles and runs C++ in your browser. Every Run button on this site opens it.

    To build the examples in this course you need a C++ compiler. You also need the right flags: by default, a compiler stays quiet about many mistakes, and a program with a bug can run and print a wrong answer without complaint. This lesson installs a compiler, turns on the warnings and run-time checks every example on this site uses, and sets up a small CMake project so you don’t have to type the flags every time.

    In 30 seconds

    • Install GCC or Clang. On Windows, install Ubuntu with WSL first, then follow the Linux steps.
    • Build with -std=c++23 -Wall -Wextra -Wpedantic -Wimplicit-fallthrough -Werror: the compiler warns about likely mistakes, and -Werror makes you fix them.
    • While you learn, add -g -fsanitize=address,undefined -fno-sanitize-recover=all: the sanitizers stop your program with a report when it breaks a rule.
    • A CMakeLists.txt keeps those flags in one place; cmake -B build and cmake --build build build the project.

    Install a compiler

    You’ll type the commands below in a terminal. You need GCC 14 or later, or a recent Clang: older versions don’t have std::println, which every lesson uses. This site checks every example with GCC 15 and Clang 21.

    Linux (Ubuntu or Debian)

    apt is the package manager. sudo runs a command as the administrator, so it asks for your password.

    sudo apt update
    sudo apt install g++ clang cmake
    g++ --version
    clang++ --version
    

    The last two commands print the version you got. If g++ is older than 14 (Ubuntu 24.04 comes with 13), install a newer one next to it and use g++-14 wherever this course says g++:

    sudo apt install g++-14
    g++-14 --version
    

    macOS

    Apple’s command line tools include Clang:

    xcode-select --install
    clang++ --version
    

    On a Mac, g++ is also Apple’s Clang under another name. Apple’s Clang can lag behind the newest C++ features. If #include <print> fails, install the newest Clang with Homebrew, and follow the notes brew info llvm prints about putting it on your PATH:

    brew install llvm cmake
    brew info llvm
    

    Windows

    This course uses Linux commands, so install Ubuntu inside Windows with WSL. In PowerShell, opened with “Run as administrator”, run:

    wsl --install
    

    Restart when it asks, open Ubuntu from the Start menu, and follow the Linux steps above. Your Windows files are under /mnt/c/ inside Ubuntu.

    Windows also has Microsoft’s own compiler, MSVC, which comes with Visual Studio. It’s a fine compiler, but it uses different flags (/W4 instead of -Wall, for example), and this course only shows the GCC and Clang ones.

    The flags this course uses

    Every example on this site is built with these flags, and you should build your own code with them while you learn:

    g++ -std=c++23 -Wall -Wextra -Wpedantic -Wimplicit-fallthrough -Werror -g -O0 -fsanitize=address,undefined -fno-sanitize-recover=all hello.cpp -o hello
    
    FlagWhat it does
    -std=c++23Use C++23, the version of C++ this course teaches.
    -WallTurn on the most useful warnings. Despite its name, it isn’t all of them.
    -WextraTurn on more warnings.
    -WpedanticWarn about features that only this compiler accepts, so your code works with any compiler.
    -Wimplicit-fallthroughWarn when a case in a switch runs on into the next one without a break. GCC already includes it in -Wextra; Clang needs it named.
    -WerrorTreat every warning as an error: the build fails until you fix it.
    -gKeep the names of your files and lines in the program, so reports can point at them.
    -O0Don’t optimize: the program does what each line says, in order. Easiest to debug.
    -fsanitize=address,undefinedBuild AddressSanitizer and UndefinedBehaviorSanitizer into the program.
    -fno-sanitize-recover=allStop the program at the first problem. Without it, UndefinedBehaviorSanitizer prints its report and lets the program carry on.

    clang++ takes the same flags. Swap g++ for clang++ in any command in this course.

    Warnings, and making them errors

    A warning means “this compiles, but it’s probably not what you meant”. Here’s a classic. unsigned int is a whole number that can’t be negative. To compare it with a plain int, C++ first converts the int to unsigned int, and -1 becomes a very large number. With these flags, the compiler warns, and -Werror turns the warning into an error:

    #include <print>
    
    int balance = -1;
    unsigned int limit = 1;
    if (balance < limit) {
        std::println("under the limit");
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:5:13: error: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Werror=sign-compare]
        5 | if (balance < limit) {
          |     ~~~~~~~~^~~~~~~
    cc1plus: all warnings being treated as errors

    Here’s what happens if you switch that warning off with -Wno-sign-compare:

    #include <print>
    
    int balance = -1;
    unsigned int limit = 1;
    std::println("{}", balance < limit);

    Output

    false

    balance < limit is false, even though -1 is less than 1. The program builds and runs, and the answer is wrong. Integers and floating-point numbers explains why, and how to compare the two safely.

    Without -Werror, the warning scrolls past, the build succeeds and you run the program anyway. With -Werror, you can’t miss it.

    Key ideaTreat warnings as bugs

    Almost every warning points at a real mistake or at code that’s easy to misread. Keep -Werror on, and fix the code rather than switching the warning off.

    Sanitizers: catching bugs while the program runs

    Some mistakes can’t be seen when the program is compiled, because they depend on the values it meets while running. Many of them are undefined behavior: C++ doesn’t say what happens, so the program might crash, print a wrong result, or seem fine until it isn’t. Sanitizers add checks to your program that catch these mistakes the moment they happen.

    A number too big for its type

    On the platform this course uses (64-bit Linux), an int holds whole numbers up to about 2.1 billion. Adding two billion to two billion doesn’t fit:

    #include <print>
    
    int reads = 2000000000;
    int more_reads = 2000000000;
    int total = reads + more_reads;
    std::println("{}", total);

    This fails when it runs

    main.cpp:5:19: runtime error: signed integer overflow: 2000000000 + 2000000000 cannot be represented in type 'int'

    UndefinedBehaviorSanitizer stops the program and names the file, the line, the numbers and the type. The fix is a type with room for the result. long long holds whole numbers up to about 9 quintillion; Integers and floating-point numbers covers all the sizes.

    #include <print>
    
    long long reads = 2000000000;
    long long more_reads = 2000000000;
    long long total = reads + more_reads;
    std::println("{}", total);

    Output

    4000000000

    Reading past the end of an array

    int readings[3] is an array: three ints side by side, at indexes 0, 1 and 2. The for loop below runs its body once for each i, starting at 0 and adding 1 each time (++i) while the condition in the middle holds; total += readings[i] adds one reading to total. Control flow covers loops in full. The loop uses <= where it means <, so its last step reads readings[3], which doesn’t exist:

    #include <print>
    
    int readings[3] = {7, 8, 9};
    int total = 0;
    for (int i = 0; i <= 3; ++i) {
        total += readings[i];
    }
    std::println("{}", total);

    This fails when it runs

    main.cpp:6:24: runtime error: index 3 out of bounds for type 'int [3]'

    The fix is i < 3:

    #include <print>
    
    int readings[3] = {7, 8, 9};
    int total = 0;
    for (int i = 0; i < 3; ++i) {
        total += readings[i];
    }
    std::println("{}", total);

    Output

    24

    Arrays, std::array and std::span shows safer ways to loop over an array, so you can’t get the bound wrong.

    Undefined behaviorWithout sanitizers, nothing may happen

    Built without -fsanitize, both broken programs above usually run to the end and print a number. Nothing tells you it’s wrong. That’s why every example on this site runs with sanitizers, and why you should use them for all your code while you learn.

    PerformanceSanitizers are for testing, not shipping

    The extra checks make a program slower (AddressSanitizer often about twice as slow) and use more memory. Use them while you write and test code, and build the version you ship without them.

    A minimal CMake project

    Typing all those flags gets old, and a real project has many source files. CMake reads a short description of your project and writes the build commands for you. Make a folder with two files: main.cpp (the hello program from How a C++ program is built) and CMakeLists.txt:

    # CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(hello LANGUAGES CXX)
    
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_CXX_EXTENSIONS OFF)
    
    add_executable(hello main.cpp)
    
    target_compile_options(hello PRIVATE -Wall -Wextra -Wpedantic -Wimplicit-fallthrough -Werror)
    
    if(CMAKE_BUILD_TYPE STREQUAL "Debug")
        target_compile_options(hello PRIVATE
            -fsanitize=address,undefined -fno-sanitize-recover=all)
        target_link_options(hello PRIVATE -fsanitize=address,undefined)
    endif()
    

    Line by line:

    • cmake_minimum_required names the oldest CMake that can read this file. project names the project and says it’s C++ (CXX).
    • The three set lines ask for C++23, refuse to build with anything older, and use standard C++ only (-std=c++23, not GCC’s own variant).
    • add_executable says: build a program called hello from main.cpp. List more source files after it as your project grows.
    • target_compile_options adds the warning flags to every build of hello.
    • For a Debug build, it also adds the sanitizers. They go in target_link_options too, because the linker has to add the sanitizers’ own code to the program. -fno-sanitize-recover=all stops the program at the first problem instead of carrying on.

    Then build and run:

    cmake -B build -DCMAKE_BUILD_TYPE=Debug
    cmake --build build
    ./build/hello
    

    The first command sets up a build folder for everything CMake makes, as a Debug build (which also adds -g). You run it once. The second command builds, and recompiles only the files you’ve changed since last time. For a fast version without sanitizers, use a second folder:

    cmake -B build-release -DCMAKE_BUILD_TYPE=Release
    cmake --build build-release
    

    Module 8 covers CMake properly: libraries, several programs in one project, and tests.

    The Run button on this site

    Every example has a Run button. It opens the example in Compiler Explorer (godbolt.org) with the same compiler and flags the site uses: GCC 15.2, -std=c++23, the warnings, and the sanitizers. There, you can change the code and run it again, with nothing to install. Examples that must not compile have an Open button instead, so you can see the error and try a fix.

    Two differences from the commands above:

    • Compiler Explorer shows warnings without -Werror, so you can still run the program and see what the warning was about.
    • Before publishing, this site builds every example with both GCC 15 and Clang 21 (with -Werror, plus -Wno-unused so a short example may declare a variable it never uses), runs it with the sanitizers on Linux, and checks that the output matches the page. The error messages and sanitizer reports you see under the failing examples are the real ones.

    Your code goes to Compiler Explorer only when you press Run. Offline, the button tells you it needs a connection.

    Which one should I use?

    WhatWhenWhyHow
    The Run buttonReading a lesson, trying a small change.Nothing to install, same compiler and flags as the page.Press Run on any example.
    One g++ commandA single-file program on your own machine.Quick, and you see every flag.g++ -std=c++23 -Wall -Wextra -Wpedantic -Wimplicit-fallthrough -Werror -g -fsanitize=address,undefined -fno-sanitize-recover=all app.cpp -o app
    CMakeAnything with more than one file, or that you’ll keep working on.Flags live in one file; only changed files are rebuilt; Debug and Release builds side by side.cmake -B build -DCMAKE_BUILD_TYPE=Debug, then cmake --build build

    Rule of thumb: try ideas with the Run button, and use CMake with a Debug build for your own projects. Keep warnings as errors and sanitizers on until the code is ready to ship.

    Under the hood

    A sanitizer works at compile time and at run time together. When you build with -fsanitize=address,undefined, the compiler adds a small check before each risky operation in your code. Before reading or writing memory, AddressSanitizer checks that the address belongs to something your program may use. Before indexing an array whose size it knows, or adding two ints, UndefinedBehaviorSanitizer checks that the index is inside the array, or that the result fits. The -fsanitize flag at link time adds the sanitizer’s own library, which keeps track of which memory your program may use and prints the report when a check fails.

    That’s why sanitizers only find bugs on lines the program actually runs, with the values it actually meets. A test that never takes the broken path reports nothing. It’s also why they cost speed and memory, and why the warnings and the sanitizers work best together: warnings catch what can be seen in the code, sanitizers catch what only shows up when it runs.

    Common pitfalls

    Forgetting -std=c++23

    Without -std=c++23, a compiler uses an older version of C++ (GCC 15 defaults to C++17), and newer parts of the standard library, like std::println, are missing. Here, -std=c++20 stands in for an older version:

    #include <print>
    
    int main() {
        std::println("Hello, world!");
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:4:10: error: ‘println’ is not a member of ‘std’
        4 |     std::println("Hello, world!");
          |          ^~~~~~~
    main.cpp:4:10: note: ‘std::println’ is only available from C++23 onwards

    GCC’s note tells you what’s going on: std::println is only available from C++23. The fix is to say -std=c++23 (or set(CMAKE_CXX_STANDARD 23) in CMake).

    A function that forgets to return

    grade promises to return an int, but when score is below 50 it reaches its closing brace without a return. Running off the end of a function that should return a value is undefined behavior. GCC and Clang warn, and with -Werror it doesn’t build:

    #include <print>
    
    int grade(int score) {
        if (score >= 50) {
            return 1;
        }
    }
    
    int main() {
        std::println("{}", grade(70));
    }

    The compiler rejects this

    main.cpp: In function ‘int grade(int)’:
    main.cpp:7:1: error: control reaches end of non-void function [-Werror=return-type]
        7 | }
          | ^
    cc1plus: all warnings being treated as errors

    The fix is to return a value on every path: add return 0; before the closing brace. (main is the exception: it returns 0 if it reaches its closing brace.)

    Common pitfallSanitizer flags go to the linker too

    If you compile with -fsanitize=address,undefined -c and then link without it, the link fails with a long list of undefined reference errors for the sanitizer’s own functions. Pass the same -fsanitize flag to both steps; in CMake, that’s target_compile_options and target_link_options.

    Try it yourself

    Try it yourself

    This starter adds two scores and works. Add a third score of 1000000000 to the array (and change both 2s to 3). Build it: the sanitizer reports a signed integer overflow. Then fix the program so it prints the right total.

    #include <print>
    
    int main() {
        int scores[2] = {1000000000, 1000000000};
        int total = 0;
        for (int i = 0; i < 2; ++i) {
            total += scores[i];
        }
        std::println("{}", total);
    }

    Expected output

    3000000000
    Show a hint

    Each loop step adds one score, so the total grows past what an int can hold. Change the type of total so it has more room.

    Show a solution
    #include <print>
    
    int main() {
        int scores[3] = {1000000000, 1000000000, 1000000000};
        long long total = 0;
        for (int i = 0; i < 3; ++i) {
            total += scores[i];
        }
        std::println("{}", total);
    }

    The three scores add up to 3000000000, which is more than an int can hold (about 2.1 billion), so the sanitizer stops the program with signed integer overflow on the third step. With long long total, each score is converted to long long before it's added, and the sum fits.

    Saved in this browser only.