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. A minimal CMakeLists.txt
    4. Configure, then build
    5. Libraries: add_library
    6. What PUBLIC and PRIVATE pass on
    7. Warnings and sanitizers per build type
    8. Libraries someone else wrote: find_package
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. Forgetting target_link_libraries
    13. Making the include folder PRIVATE
    14. Try it yourself

    Module 8 · Organizing a project

    8.2CMake and libraries

    Describe your project once in a CMakeLists.txt and let CMake build it: configure and build steps, libraries your programs link to, what PUBLIC and PRIVATE pass on, warnings and sanitizers per build type, and libraries someone else wrote.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. A minimal CMakeLists.txt
    4. Configure, then build
    5. Libraries: add_library
    6. What PUBLIC and PRIVATE pass on
    7. Warnings and sanitizers per build type
    8. Libraries someone else wrote: find_package
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. Forgetting target_link_libraries
    13. Making the include folder PRIVATE
    14. Try it yourself

    Key terms

    build system
    A tool that works out which files need compiling, in what order, and runs the compiler and linker for you. CMake writes the instructions; a tool such as Ninja carries them out.
    configure
    CMake's first step: it reads CMakeLists.txt, finds your compiler and writes build files into the build folder.
    build folder
    The folder, often build/, that holds everything CMake makes: build files, object files, libraries and programs. You can delete it at any time and configure again.
    target
    Something CMake builds, an executable or a library, with its own source files, flags and dependencies.
    static library
    An archive of object files, such as libdna.a. The linker copies the parts a program uses into the program.
    shared library
    A library, such as libdna.so, that is loaded when the program starts. Programs that use it share one copy, and it can be updated without relinking them.
    PUBLIC, PRIVATE and INTERFACE
    Words in target_… commands. A PRIVATE setting applies to the target itself; a PUBLIC one also passes to every target that links to it; an INTERFACE one passes only to those targets.
    package
    A library installed on your machine together with files that tell CMake how to use it. find_package looks for one.

    A program with three source files builds with one g++ command. With thirty files, the right flags, a library shared by two programs and a test program, the commands get long, and running all of them after every change wastes minutes. A build system keeps track of what depends on what and rebuilds only what changed. This lesson uses CMake, the build system most C++ projects use, to build a library and a program that links to it.

    In 30 seconds

    • CMakeLists.txt describes targets: programs (add_executable) and libraries (add_library), with their source files.
    • cmake -B build configures once; cmake --build build builds, recompiling only what changed. Everything goes in the build folder.
    • target_link_libraries(gc PRIVATE dna) links a program to a library. PUBLIC settings on the library, such as its include folder, pass on to whoever links to it.
    • Warnings and sanitizers go on targets with target_compile_options; the build type (Debug or Release) picks the rest.

    A minimal CMakeLists.txt

    Setting up showed this file. Here’s the smallest useful version again; every project starts with these lines:

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(gc LANGUAGES CXX)
    
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_CXX_EXTENSIONS OFF)
    
    add_executable(gc main.cpp)
    main.cpp
    #include <algorithm>
    #include <print>
    #include <string_view>
    
    int main() {
        std::string_view read = "GATTACA";
        auto gc = std::ranges::count(read, 'G') + std::ranges::count(read, 'C');
        std::println("{}: {} of {} bases are G or C", read, gc, read.size());
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/gc

    Output

    GATTACA: 2 of 7 bases are G or C
    • cmake_minimum_required names the oldest CMake that can read the file, and turns on that version’s behavior. project names the project and says it uses C++ (CXX).
    • CMAKE_CXX_STANDARD 23 asks for C++23. CMAKE_CXX_STANDARD_REQUIRED ON makes configuring fail if the compiler can’t do C++23, instead of quietly using an older standard. CMAKE_CXX_EXTENSIONS OFF asks for -std=c++23 rather than GCC’s own dialect, -std=gnu++23. Some later examples leave out one or both of these two lines to stay short; keep them in your own projects.
    • add_executable(gc main.cpp) declares a target: a program called gc, built from main.cpp. List every source file of the program after the name.

    Configure, then build

    Building with CMake takes two commands. Run them in the folder that holds CMakeLists.txt:

    cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug   # configure
    cmake --build build                                # build
    ./build/gc
    

    Configure (cmake -B build) reads CMakeLists.txt, finds a compiler, checks that it works, and writes build files into the folder build. -G Ninja picks Ninja, a small, fast tool that runs the build files; without it, CMake writes files for Make on Linux and macOS. -DCMAKE_BUILD_TYPE=Debug sets a variable: here, the build type. You configure once per build folder.

    Build (cmake --build build) runs Ninja, which compiles and links whatever is out of date. Change main.cpp and build again, and only main.cpp is recompiled. Change a header, and every source file that includes it is recompiled: the compiler records which headers each file read. Change CMakeLists.txt, and the build configures again by itself first.

    Common pitfallThe build folder is disposable

    The build folder holds only things CMake made: keep it out of version control, and never edit files in it. When a build gets confused, delete the folder and configure again. Keep one folder per build type, such as build for Debug and build-release for Release.

    Libraries: add_library

    A library is a target other targets link to. Put the code that does the work in a library, and every program and test that needs it links the same compiled code, instead of listing its source files again. Here the dna library from Headers, source files and the one-definition rule gets its own folders, and a program gc prints the GC content of each read in a file:

    5 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(dna_tools LANGUAGES CXX)
    
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    set(CMAKE_CXX_EXTENSIONS OFF)
    
    add_library(dna src/dna.cpp)
    target_include_directories(dna PUBLIC include)
    
    add_executable(gc apps/gc.cpp)
    target_link_libraries(gc PRIVATE dna)
    include/dna.h
    #pragma once
    
    #include <string_view>
    
    namespace dna {
    
    int count_gc(std::string_view sequence);
    double gc_percent(std::string_view sequence);
    
    } // namespace dna
    src/dna.cpp
    #include "dna.h"
    
    int dna::count_gc(std::string_view sequence) {
        int count = 0;
        for (char base : sequence) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    
    double dna::gc_percent(std::string_view sequence) {
        return 100.0 * count_gc(sequence) / static_cast<double>(sequence.size());
    }
    apps/gc.cpp
    #include <fstream>
    #include <print>
    #include <string>
    
    #include "dna.h"
    
    int main(int argc, char** argv) {
        if (argc != 2) {
            std::println("usage: gc <file>");
            return 1;
        }
        std::ifstream file(argv[1]);
        std::string line;
        while (std::getline(file, line)) {
            std::println("{} {:.1f}%", line, dna::gc_percent(line));
        }
    }
    reads.txt
    GATTACA
    GGCCGGCC
    ATATAT

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/gc reads.txt

    Output

    GATTACA 28.6%
    GGCCGGCC 100.0%
    ATATAT 0.0%
    • add_library(dna src/dna.cpp) makes a library target called dna. By default (unless the variable BUILD_SHARED_LIBS is on) it’s a static library: an archive, libdna.a, of the library’s object files.
    • target_include_directories(dna PUBLIC include) adds -I include when compiling dna, and, because it’s PUBLIC, when compiling anything that links to dna. That’s how apps/gc.cpp finds "dna.h".
    • target_link_libraries(gc PRIVATE dna) links gc to dna, and gives gc everything dna marked PUBLIC.

    When the linker builds gc, it copies the parts of libdna.a that gc uses into the program. The finished gc doesn’t need libdna.a any more.

    add_library(dna SHARED src/dna.cpp) makes a shared library, libdna.so (.dylib on macOS, .dll on Windows), instead. It isn’t copied into the program: the program records that it needs libdna.so, and the operating system loads the library each time the program starts. Several programs share one copy, and you can update the library without relinking them. The price is one more file that must be found at run time, and a library whose changes can break programs that were built against an older version. Use static libraries for your own code by default. Module 11 makes a shared library that Python loads.

    What PUBLIC and PRIVATE pass on

    The target_… commands take a word that says who a setting is for:

    • PRIVATE: the setting is for this target only. Use it for anything the target’s own .cpp files need but its users don’t: a warning flag, a header folder used only inside src/, a library used only inside the .cpp files.
    • PUBLIC: for this target and everyone who links to it. Use it when the target’s headers need the setting: the folder those headers are in, or a library whose types appear in them.
    • INTERFACE: only for those who link to it. A header-only library, add_library(dna_constants INTERFACE), has nothing to compile, so all its settings are INTERFACE.

    The word in target_link_libraries decides whether a library’s settings travel further. If a library stats links dna PRIVATE, a program that links stats doesn’t get dna’s include folder. Link it PUBLIC when stats’s own headers include dna.h.

    The folders above follow a common project layout. CMake doesn’t require it, but most projects look something like it. Keep main small and the work in the library, so a test program can link the same library:

    dna_tools/
      CMakeLists.txt
      include/dna.h      # the library's headers: what users include
      src/dna.cpp        # the library's source files
      apps/gc.cpp        # programs: a small main that calls the library
      tests/             # test programs (Testing)
    

    Warnings and sanitizers per build type

    The compiler flags belong on targets too. This version turns on the warnings for every build, and the sanitizers only for a Debug build:

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(counts LANGUAGES CXX)
    
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    
    add_executable(app main.cpp)
    target_compile_options(app PRIVATE -Wall -Wextra -Wpedantic -Werror)
    
    if(CMAKE_BUILD_TYPE STREQUAL "Debug")
        target_compile_options(app PRIVATE
            -fsanitize=address,undefined -fno-sanitize-recover=all)
        target_link_options(app PRIVATE -fsanitize=address,undefined)
    endif()
    main.cpp
    #include <print>
    
    int main() {
        int counts[4] = {3, 1, 4, 1};
        int total = 0;
        for (int i = 0; i <= 4; ++i) {
            total += counts[i];
        }
        std::println("{}", total);
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    This fails when it runs

    main.cpp:7:26: runtime error: index 4 out of bounds for type 'int [4]'

    The Debug build stops at the bad read. A Release build of the same code has no sanitizers: it may print a wrong total and say nothing, or do anything else, since it’s undefined behavior. That’s why you test with Debug.

    • target_compile_options adds flags when compiling the target’s files; target_link_options adds them when linking. The sanitizers need both, because the linker adds their run-time code.
    • CMAKE_BUILD_TYPE is the variable you set with -DCMAKE_BUILD_TYPE=…. With GCC and Clang, Debug adds -g, and Release adds -O3 -DNDEBUG, which optimizes and turns assert off (Undefined behavior). RelWithDebInfo is -O2 -g -DNDEBUG: fast, but still debuggable. With no build type, CMake adds none of these: no optimization and no -g.

    Libraries someone else wrote: find_package

    A library installed on your machine usually comes with files that tell CMake where its headers and library files are, or CMake has its own file for finding it (as it does for bzip2, below): a package. find_package finds it, and makes a target for it that you link to like your own. Testing does this with the Catch2 test library: find_package(Catch2 3 REQUIRED), then target_link_libraries(tests PRIVATE Catch2::Catch2WithMain).

    REQUIRED stops configuring when the package is missing. bzip2, the library that reads .bz2 files such as compressed FASTQ reads, isn’t installed on the machine that checks this site’s examples:

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(app LANGUAGES CXX)
    
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    
    find_package(BZip2 REQUIRED)
    add_executable(app main.cpp)
    target_link_libraries(app PRIVATE BZip2::BZip2)
    main.cpp
    #include <bzlib.h>
    #include <print>
    
    int main() {
        std::println("bzip2 {}", BZ2_bzlibVersion());
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    The compiler rejects this

    -- The CXX compiler identification is GNU 15.2.0
    -- Detecting CXX compiler ABI info
    -- Detecting CXX compiler ABI info - done
    -- Check for working CXX compiler: /usr/bin/g++ - skipped
    -- Detecting CXX compile features
    -- Detecting CXX compile features - done
    -- Configuring incomplete, errors occurred!
    CMake Error at /usr/share/cmake-4.2/Modules/FindPackageHandleStandardArgs.cmake:290 (message):
      Could NOT find BZip2 (missing: BZIP2_LIBRARIES BZIP2_INCLUDE_DIR)
    Call Stack (most recent call first):
      /usr/share/cmake-4.2/Modules/FindPackageHandleStandardArgs.cmake:654 (_FPHSA_FAILURE_MESSAGE)
      /usr/share/cmake-4.2/Modules/FindBZip2.cmake:132 (find_package_handle_standard_args)
      CMakeLists.txt:7 (find_package)

    The error comes from the configure step, before anything compiles. Install the library’s development files, which hold its headers and CMake files (sudo apt install libbz2-dev on Ubuntu, brew install bzip2 on macOS), and configure again. For a library that isn’t installed, CMake’s FetchContent module can download its source code while configuring and build it as part of your project, pinned to a version you choose. It’s handy for small libraries and test frameworks; it needs a network connection the first time.

    Which one should I use?

    WhatWhenWhyHow
    Sources in add_executableOne small program.Nothing to set up.add_executable(gc main.cpp dna.cpp)
    Static libraryCode that a program and its tests (or several programs) share.Compiled once; the finished program stands alone.add_library(dna src/dna.cpp) and target_link_libraries(gc PRIVATE dna)
    Shared libraryA big library many programs load, or one another language loads.One copy on disk and in memory; can be updated without relinking.add_library(dna SHARED src/dna.cpp)
    find_packageA library installed on the machine.Its own CMake files say how to use it.find_package(Catch2 3 REQUIRED)

    Rule of thumb: put the work in a static library with a thin program on top, link with PRIVATE, and make a setting PUBLIC only when your library’s headers need it.

    Under the hood

    cmake --build build --verbose prints every command Ninja runs. For the dna_tools project, built as Debug, they come down to three kinds:

    • Compiling: c++ -I/…/include -g -std=c++23 … -c src/dna.cpp, and the same for apps/gc.cpp. Both get -I…/include, because dna made it PUBLIC. Each source file becomes an object file in build/CMakeFiles/.
    • Archiving: ar qc libdna.a …/dna.cpp.o. A static library is a bundle of object files made by ar, the archiver.
    • Linking: c++ -g …/gc.cpp.o -o gc libdna.a. This is the link step from How a C++ program is built, with the library listed after the object file that needs it.

    With CMake 3.28 or later and Ninja, you’ll also see lines that scan each file for C++ modules, which Modules explains. Configure also writes CMakeCache.txt (every variable’s value, such as CMAKE_BUILD_TYPE) and build.ninja (the rules Ninja follows). Editors and tools such as clangd and clang-tidy need to know the exact flags for each file; ask CMake to write them down:

    cmake -B build -G Ninja -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
    ls build/compile_commands.json
    

    compile_commands.json lists the command for every source file. Point your editor at it, and its errors and completions match your real build.

    Common pitfalls

    The library and the program are both declared, but nothing links them. Everything compiles, because main.cpp finds the header next to it, and then the link fails:

    4 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(gc LANGUAGES CXX)
    
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    
    add_library(dna dna.cpp)
    add_executable(gc main.cpp)
    dna.h
    #pragma once
    
    bool is_gc(char base);
    dna.cpp
    #include "dna.h"
    
    bool is_gc(char base) {
        return base == 'G' || base == 'C';
    }
    main.cpp
    #include <print>
    
    #include "dna.h"
    
    int main() {
        std::println("{}", is_gc('A'));
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    The compiler rejects this

    ld: main.cpp.o: in function `main':
    main.cpp:6: undefined reference to `is_gc(char)'
    collect2: error: ld returned 1 exit status

    Add target_link_libraries(gc PRIVATE dna). A misspelled target name in that line, such as dnaa, fails at link time too: CMake takes a name it doesn’t know as a library file to look for, and the linker can’t find it.

    Making the include folder PRIVATE

    dna’s header folder is PRIVATE, so dna itself compiles, but gc doesn’t get -I include:

    4 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(dna_tools LANGUAGES CXX)
    
    set(CMAKE_CXX_STANDARD 23)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    
    add_library(dna src/dna.cpp)
    target_include_directories(dna PRIVATE include)
    
    add_executable(gc apps/gc.cpp)
    target_link_libraries(gc PRIVATE dna)
    include/dna.h
    #pragma once
    
    bool is_gc(char base);
    src/dna.cpp
    #include "dna.h"
    
    bool is_gc(char base) {
        return base == 'G' || base == 'C';
    }
    apps/gc.cpp
    #include <print>
    
    #include "dna.h"
    
    int main() {
        std::println("{}", is_gc('A'));
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    The compiler rejects this

    apps/gc.cpp:3:10: fatal error: dna.h: No such file or directory
        3 | #include "dna.h"
          |          ^~~~~~~
    compilation terminated.

    The folder holds the library’s public header, which its users include, so it’s PUBLIC.

    Try it yourself

    Try it yourself

    A Release build defines NDEBUG, which turns assert off. Make this program print checks: on or checks: off on its first line, so you can tell which build you’re running. Then build it with CMake into build as Debug and into build-release as Release, and run both.

    #include <cassert>
    #include <numeric>
    #include <print>
    #include <vector>
    
    double mean(const std::vector<double>& values) {
        assert(!values.empty());
        double total = std::accumulate(values.begin(), values.end(), 0.0);
        return total / static_cast<double>(values.size());
    }
    
    int main() {
        std::println("{}", mean({30.0, 40.0}));
    }

    Expected output

    checks: on
    35
    Show a hint

    #ifdef NDEBUG is true in a Release build, because CMake passes -DNDEBUG. Put #ifdef NDEBUG, #else and #endif around two std::println lines at the top of main.

    Show a solution
    #include <cassert>
    #include <numeric>
    #include <print>
    #include <vector>
    
    double mean(const std::vector<double>& values) {
        assert(!values.empty());
        double total = std::accumulate(values.begin(), values.end(), 0.0);
        return total / static_cast<double>(values.size());
    }
    
    int main() {
    #ifdef NDEBUG
        std::println("checks: off");
    #else
        std::println("checks: on");
    #endif
        std::println("{}", mean({30.0, 40.0}));
    }

    NDEBUG is a macro that Release and RelWithDebInfo builds define and Debug builds don't. assert looks at it, and so can your code. On this site the example runs like a Debug build, so it prints checks: on; in build-release it prints checks: off, and the assert in mean is gone.

    Saved in this browser only.