TExcelTAD

CMake Intro

CMake is the most widely used build system for C and C++. Strictly speaking it is a build system generator: you describe your project once in CMakeLists.txt, and CMake writes the files that a real build tool runs: a build.ninja for Ninja, Makefiles for GNU Make, a Visual Studio solution, an Xcode project. The same description builds on Linux, Windows and macOS, with GCC, Clang or MSVC.

This course teaches modern, target-based CMake (CMake 3.x style, current with CMake 4.4): every library and executable is a target that carries its own sources, include directories, compile options and dependencies, and consumers inherit exactly what they need. Then it covers the rest of the CMake family: CTest runs tests, CPack turns an install into packages.

The three steps

A CMake build always happens in three steps:

Step Command What happens
Configure cmake -S . -B build CMake runs your CMakeLists.txt, detects the compiler, finds dependencies and stores the results in build/CMakeCache.txt
Generate (part of the same command) CMake writes the native build files (build/build.ninja)
Build cmake --build build the native tool (Ninja) compiles and links; CMake re-runs itself automatically when a CMakeLists.txt changed

-S names the source directory (where the top-level CMakeLists.txt is) and -B the build directory. All generated files go into the build directory, so you can delete it at any time and start over, and you can have several of them side by side (Debug and Release, GCC and Clang).

A first session

Here is the whole cycle with a one-file program. Every session in this course is a real run with CMake 4.4.4, Ninja 1.13 and GCC 13 on Ubuntu 24.04, and the output under it is what the tools printed:

bash · try it yourself
mkdir -p hello && cd hello
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Hello LANGUAGES CXX)
add_executable(hello main.cpp)
CM
cat > main.cpp <<'SRC'
#include <iostream>
int main() { std::cout << "Hello from CMake\n"; }
SRC
cmake -S . -B build -G Ninja
cmake --build build
./build/hello
-- The CXX compiler identification is GNU 13.3.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done (0.3s)
-- Generating done (0.0s)
-- Build files have been written to: /home/learner/hello/build
[1/2] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[2/2] Linking CXX executable hello
Hello from CMake

Three lines of CMake did a lot:

  • cmake_minimum_required says which CMake versions the project was written for. It also selects the behaviour (the policies) CMake uses, so it is always the first line.
  • project() names the project and enables the C++ language. That is what triggered the compiler detection: CMake found /usr/bin/c++, identified it as GCC 13.3, and checked its ABI and the C++ standards it supports.
  • add_executable(hello main.cpp) creates a target named hello built from main.cpp.

-G Ninja picks the generator. Without it CMake on Linux defaults to Unix Makefiles; this course uses Ninja throughout, as most modern projects do (the Generators lesson compares them). Ninja printed one line per build step: [1/2] compiled the source, [2/2] linked the program.

Note: Times such as (0.2s) in configure output differ from run to run. Everything else in these sessions is deterministic.

Quieter configure output

The compiler detection lines are the same in every session, so from the next lessons on most sessions configure with --log-level=NOTICE. That hides CMake's -- status lines but keeps warnings, errors and your own message() output, leaving only the three closing lines:

bash · try it yourself
mkdir -p hello && cd hello
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Hello LANGUAGES CXX)
add_executable(hello main.cpp)
message("configuring ${PROJECT_NAME} with CMake ${CMAKE_VERSION}")
CM
echo 'int main() { return 0; }' > main.cpp
cmake -S . -B build -G Ninja --log-level=NOTICE
cmake --build build
configuring Hello with CMake 4.4.4
-- Configuring done (0.2s)
-- Generating done (0.0s)
-- Build files have been written to: /home/learner/hello/build
[1/2] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[2/2] Linking CXX executable hello

What this course covers

Section The question it answers
Getting Started How do I configure and build? What does the CMake language look like? Which generator and build type?
Targets How do I build executables and libraries, and how do include paths, definitions and link dependencies travel between them?
Dependencies How do I use libraries someone else built (find_package) or that I build from source (FetchContent)?
Install & Export How do I install my library so another project can find_package() it?
Configuration Generator expressions, options and cache variables, generated headers, platform checks
Advanced Builds Toolchain files and cross-compiling, presets, code generation, policies and CMake 4
CTest and CPack Registering and running tests; turning an install into .tar.gz and .deb packages
Toolkit and Field Notes Inspection and debugging tools, IDE integration, ccache, and the anti-patterns to avoid
Mini Project An installable library + app with presets, tests and a package, consumed by a second project

Where CMake sits

Below CMake are the build tools from GNU Make & Ninja and the compiler and linker steps from Build Fundamentals. Above it are package managers: Conan, vcpkg and CPM.cmake are taught in C/C++ Packages, which builds directly on this course. Alternatives such as Meson and xmake are in Meson, Autotools & xmake.

Runnable models

CMake itself can't run in your browser, so the sessions are recorded. Wherever an idea is easier to understand by poking at it, the lesson adds a small runnable model in JavaScript that you can edit and run. Here is the first one: the three steps as a tiny pipeline, where "configure" produces a cache and "generate" turns targets into build statements.

js · try it yourself
const project = {
  name: 'Hello',
  targets: [{ name: 'hello', kind: 'executable', sources: ['main.cpp'] }],
};

function configure(p) {
  // Real CMake detects the compiler here and stores the answers in CMakeCache.txt.
  return { CMAKE_CXX_COMPILER: '/usr/bin/c++', CMAKE_PROJECT_NAME: p.name };
}

function generate(p, cache) {
  const lines = [];
  for (const t of p.targets) {
    const objects = t.sources.map((s) => `CMakeFiles/${t.name}.dir/${s}.o`);
    t.sources.forEach((s, i) => lines.push(`build ${objects[i]}: CXX_COMPILER ${s}`));
    lines.push(`build ${t.name}: CXX_EXECUTABLE_LINKER ${objects.join(' ')}`);
  }
  return { cache, ninja: lines };
}

const { cache, ninja } = generate(project, configure(project));
console.log('cache:', cache);
console.log(ninja.join('\n'));
cache: { CMAKE_CXX_COMPILER: '/usr/bin/c++', CMAKE_PROJECT_NAME: 'Hello' }
build CMakeFiles/hello.dir/main.cpp.o: CXX_COMPILER main.cpp
build hello: CXX_EXECUTABLE_LINKER CMakeFiles/hello.dir/main.cpp.o

Test yourself

What does cmake -S . -B build do?

  1. Compiles the project into ./build
  2. Configures the project in the current directory and generates native build files in ./build
  3. Installs the project into ./build
  4. Deletes and recreates ./build

Why is CMake called a build system *generator*?

  1. It generates source code
  2. It writes files for a native build tool such as Ninja, Make or Visual Studio, which then does the compiling
  3. It downloads compilers
  4. It generates documentation

Which command creates a target in the first example?

  1. project(Hello LANGUAGES CXX)
  2. cmake_minimum_required(VERSION 3.25)
  3. add_executable(hello main.cpp)
  4. cmake --build build