Tutorials / C++: From Basics to Modern C++ / Building projects with CMake

Building projects with CMake

16 min read cmake
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

Why a build system

Typing g++ main.cpp util.cpp parser.cpp ... works for three files. At thirty files it becomes a pain, and it also differs between g++, clang and MSVC. A build system describes the project once and produces the right build for each platform. CMake is the most widely used choice for C++. It does not compile anything itself. It generates the files for a tool that does: Makefiles, Ninja files, or a Visual Studio solution.

A minimal project

Create this layout:

greeter/
  CMakeLists.txt
  src/
    main.cpp
    greeting.cpp
    greeting.h

The two source files:

// src/greeting.h
#pragma once
#include <string>
std::string makeGreeting(const std::string& name);

// src/greeting.cpp
#include "greeting.h"
std::string makeGreeting(const std::string& name) {
    return "Hello, " + name + "!";
}

// src/main.cpp
#include <iostream>
#include "greeting.h"
int main() {
    std::cout << makeGreeting("CMake") << "\n";
}

And the build description:

cmake_minimum_required(VERSION 3.20)
project(Greeter LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(greeter
    src/main.cpp
    src/greeting.cpp
)

Building it

The recommended habit is an out-of-source build: generated files go in a separate folder, so your source tree stays clean and you can delete the build folder at any time.

cmake -S . -B build
cmake --build build
./build/greeter

The first command configures: it reads the CMakeLists.txt and generates build files into build. The second command builds. These two commands are the same on every platform. On Windows with Visual Studio, the executable ends up in build\Debug\greeter.exe because Visual Studio generators support several configurations. Choose one with cmake --build build --config Release. With single-config generators such as Ninja or Makefiles, set it when configuring: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release.

Targets are the core idea

Modern CMake is about targets: an executable or a library, together with the properties it needs. Properties are attached to a target with target_* commands. Avoid the old global commands such as include_directories and add_definitions, because they affect everything and make it hard to see what depends on what.

Let us split our project into a library and a program. The code in greeting becomes a library that other targets can use.

cmake_minimum_required(VERSION 3.20)
project(Greeter LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_library(greeting STATIC src/greeting.cpp)
target_include_directories(greeting PUBLIC src)

add_executable(greeter src/main.cpp)
target_link_libraries(greeter PRIVATE greeting)

Two keywords matter here. PUBLIC on the include directory means "I need it, and so does anyone who links me". Because of this, greeter can write #include "greeting.h" without being told where the header is. PRIVATE on target_link_libraries means the dependency is an internal detail of greeter. The third keyword, INTERFACE, means "not needed by me, but needed by my users" and is used for header-only libraries.

Warnings per compiler

Warning flags differ between compilers, and CMake gives you a way to choose.

if (MSVC)
    target_compile_options(greeter PRIVATE /W4)
else()
    target_compile_options(greeter PRIVATE -Wall -Wextra -Wpedantic)
endif()

I turn warnings on from the very beginning of a project. Turning them on in a project with ten thousand warnings is a depressing job.

Adding tests

CMake comes with a test runner called CTest. A test is just an executable that returns zero on success and non-zero on failure.

enable_testing()

add_executable(greeting_test tests/greeting_test.cpp)
target_link_libraries(greeting_test PRIVATE greeting)
add_test(NAME greeting_test COMMAND greeting_test)
// tests/greeting_test.cpp
#include <cstdlib>
#include <iostream>
#include "greeting.h"

int main() {
    if (makeGreeting("Ali") != "Hello, Ali!") {
        std::cerr << "makeGreeting returned the wrong text\n";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Build, then run ctest --test-dir build. On multi-config generators add -C Debug. For real projects most people adopt a test framework like Catch2 or GoogleTest, which you can bring in with CMake's FetchContent module or a package manager. The pattern is the same: another executable target, linked against your library, registered with add_test.

Handy extras

  • file(GLOB ...) collects sources by pattern, but it does not notice newly added files until you re-run configure. Listing files explicitly is more reliable.
  • Set CMAKE_EXPORT_COMPILE_COMMANDS ON to produce compile_commands.json, which editors use for code completion.
  • Choose a generator with -G Ninja if you have Ninja installed. It builds faster than Makefiles.
  • Presets (CMakePresets.json) store common configure options so teammates run one short command.

The common mistake

Editing files inside the build folder, or committing it to version control. It is generated output. Add build/ to .gitignore. Another frequent problem is changing the compiler or flags and reusing an old build folder, which keeps the cached values. Delete the folder and configure again. And forgetting PUBLIC on include directories, then wondering why dependants cannot find the header.

Try it yourself

  1. Create the greeter project above, build it with cmake -S . -B build, and run it.
  2. Split it into a library and an executable, and check that greeter finds the header only through the link line.
  3. Add the test target and run ctest. Break the greeting text on purpose and confirm the test fails.
cmake
greeter/
  CMakeLists.txt
  src/
    main.cpp
    greeting.cpp
    greeting.h

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account