Skip to content
Tutorials Center
My learning

Topics

Lesson 144 of 171 ยท Modern C++ and Beyond

Build Systems: Make and CMake

Learn how C++ projects are built - incremental builds, writing a Makefile, modern CMake with targets and build types, and managing libraries with vcpkg and Conan.

Compiling one file is a single command: g++ -std=c++23 main.cpp -o app. Real projects have hundreds of source files, third-party libraries, unit tests, debug and release configurations, and developers on Linux, macOS and Windows using different compilers. Typing compiler commands by hand stops working on day two. A build system records how to build the project once, then figures out what to compile, in what order, with which flags, and, crucially, what doesn't need to be recompiled after you change one file.

This lesson explains what a build system does, writes a real Makefile, then moves to CMake, the de facto standard for C++ projects, written the modern, target-based way. It finishes with package managers (vcpkg and Conan) for pulling in libraries. Our online editor builds single files, so project files here are read-only, but the runnable examples show the ideas a build system is made of. It builds on How C++ Works: Compiling and Linking and Header Files and Multiple Source Files.

What a build system does

Recall how a multi-file program is built: each .cpp file is compiled separately into an object file, and the linker combines the object files (and libraries) into an executable.

Terminal
g++ -std=c++23 -Wall -Wextra -c main.cpp     -o main.o
g++ -std=c++23 -Wall -Wextra -c parser.cpp   -o parser.o
g++ -std=c++23 -Wall -Wextra -c report.cpp   -o report.o
g++ main.o parser.o report.o -o app          # link

Because compilation is per file, you only need to recompile the files whose inputs changed. If you edit report.cpp, only report.o is out of date, and then the link step must run again. If you edit parser.h, every .cpp file that includes it is out of date. Getting this right by hand is impossible in a big project; getting it wrong means either slow full rebuilds or, worse, stale object files and baffling bugs.

A build system therefore keeps a dependency graph (which outputs are made from which inputs) and compares timestamps or content hashes: an output is rebuilt when any input is newer. Here is that core idea in a few dozen lines, with made-up file times:

C++ The heart of make: rebuild what is out of date

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Editing report.cpp recompiles one file and relinks. Editing parser.h recompiles the two files that include it. When nothing changed, nothing runs. That's what make does, at much larger scale and in parallel (make -j8 runs independent commands at the same time). The hard part in real projects is knowing the header dependencies, which compilers can report for you (-MMD, below).

Make and Makefiles

GNU Make (1976 in its original form) is the classic Unix build tool. A Makefile lists rules: a target, the prerequisites it depends on, and the recipe (shell commands) that creates it.

MAKE
# Makefile
CXX      := g++
CXXFLAGS := -std=c++23 -Wall -Wextra -O2 -MMD -MP
LDFLAGS  :=
LDLIBS   := -pthread

SRCS := main.cpp parser.cpp report.cpp
OBJS := $(SRCS:.cpp=.o)          # main.o parser.o report.o
DEPS := $(OBJS:.o=.d)            # dependency files written by -MMD

app: $(OBJS)
	$(CXX) $(LDFLAGS) $^ -o $@ $(LDLIBS)

%.o: %.cpp
	$(CXX) $(CXXFLAGS) -c $< -o $@

.PHONY: clean
clean:
	rm -f app $(OBJS) $(DEPS)

-include $(DEPS)

How to read it:

  • app: $(OBJS) says "app depends on the object files". The indented line below is the recipe. Recipe lines must start with a tab character, not spaces; "missing separator" errors almost always mean spaces crept in.
  • %.o: %.cpp is a pattern rule: any .o file can be built from the .cpp file with the same name.
  • Automatic variables: $@ is the target, $< the first prerequisite, $^ all prerequisites.
  • -MMD -MP make GCC and Clang write a .d file next to each object, listing every header it included. -include $(DEPS) loads those lists, so editing a header rebuilds exactly the right objects. Without this, Make doesn't know about headers at all.
  • .PHONY: clean marks clean as a command, not a file.

Use it with make (build the first target), make -j8 (parallel), make clean, or make CXXFLAGS="-O0 -g" to override a variable for one run.

Make is everywhere and great for small projects, but it has limits: Makefiles are tied to a Unix shell and a particular compiler's flags, they don't work with MSVC on Windows, configuring optional features or finding installed libraries is manual work, and large Makefiles become hard to maintain. That's what CMake solves.

CMake: a build system generator

CMake doesn't build anything itself. It reads a portable project description, CMakeLists.txt, and generates the files for a native build tool: Ninja, Makefiles, Visual Studio solutions or Xcode projects. The same CMakeLists.txt builds with GCC on Linux, Clang on macOS and MSVC on Windows, and every major IDE (Visual Studio, CLion, VS Code, Qt Creator) opens CMake projects directly.

A small but realistic project:

TEXT
weather/
โ”œโ”€โ”€ CMakeLists.txt
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.cpp
โ”‚   โ””โ”€โ”€ CMakeLists.txt        (optional; small projects keep everything in one file)
โ”œโ”€โ”€ lib/
โ”‚   โ”œโ”€โ”€ include/weather/parser.h
โ”‚   โ”œโ”€โ”€ parser.cpp
โ”‚   โ””โ”€โ”€ stats.cpp
โ””โ”€โ”€ tests/
    โ””โ”€โ”€ parser_test.cpp
CMAKE
cmake_minimum_required(VERSION 3.28)
project(weather VERSION 1.2.0 LANGUAGES CXX)

# A library target: our reusable code.
add_library(weather_core
    lib/parser.cpp
    lib/stats.cpp)
target_include_directories(weather_core PUBLIC lib/include)
target_compile_features(weather_core PUBLIC cxx_std_23)

# Warnings, written per compiler with a generator expression.
target_compile_options(weather_core PRIVATE
    $<$<CXX_COMPILER_ID:MSVC>:/W4 /permissive->
    $<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-Wall -Wextra -Wpedantic>)

find_package(Threads REQUIRED)
target_link_libraries(weather_core PUBLIC Threads::Threads)

# The program, linked against the library.
add_executable(weather src/main.cpp)
target_link_libraries(weather PRIVATE weather_core)
target_compile_definitions(weather PRIVATE APP_VERSION="${PROJECT_VERSION}")

# Tests, run with ctest.
enable_testing()
add_executable(parser_test tests/parser_test.cpp)
target_link_libraries(parser_test PRIVATE weather_core)
add_test(NAME parser_test COMMAND parser_test)

The key idea of modern CMake is targets with usage requirements. A target (add_library, add_executable) carries its own include directories, compile features, definitions and dependencies, and the keyword says who they apply to:

Keyword Applies to the target itself Propagates to targets that link it
PRIVATE yes no
PUBLIC yes yes
INTERFACE no yes (used by header-only libraries)

Because weather_core declares its include directory and cxx_std_23 as PUBLIC, the weather executable and the test get them automatically just by linking it. Nobody repeats include paths or flags. Older CMake code instead sets global variables and directory-wide commands (include_directories(), add_definitions(), editing CMAKE_CXX_FLAGS); it works, but it scales badly, so prefer the target_* commands.

Configuring and building

CMake works in two steps, always in a separate build directory (an "out-of-source" build), so generated files never mix with your sources:

Terminal
# 1. Configure: pick a generator and options, write the build files into build/
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release

# 2. Build (calls ninja, make or MSBuild for you), in parallel
cmake --build build -j

# Run the tests
ctest --test-dir build --output-on-failure

CMAKE_BUILD_TYPE selects a configuration for single-config generators like Ninja and Make: Debug (-g, no optimization), Release (-O3 -DNDEBUG), RelWithDebInfo (-O2 -g -DNDEBUG) and MinSizeRel (-Os -DNDEBUG). Multi-config generators (Visual Studio, Xcode, "Ninja Multi-Config") pick it at build time instead: cmake --build build --config Release. Use one build directory per configuration, such as build-debug and build-release.

Two more conveniences used in most projects:

  • -DCMAKE_EXPORT_COMPILE_COMMANDS=ON writes compile_commands.json, the exact compiler command for every file, which clangd, clang-tidy and many editors read for accurate code completion and analysis.
  • CMakePresets.json stores named configure/build settings in the repository, so everyone (and CI) runs cmake --preset release instead of remembering flags.

Values defined with target_compile_definitions arrive in your code as macros, just like -D on the command line. Here's how a program typically reads them, with fallbacks for when it's built without them:

C++ Using values the build system passes in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Our editor compiles without -DNDEBUG or -DAPP_VERSION, so you see the development defaults and asserts are on. Keep such macros few and simple; for anything more structured, CMake's configure_file() can generate a small header (for example version.h) from a template.

Dependencies: finding and fetching libraries

Using a third-party library means finding its headers, its compiled library files and its own dependencies, on every platform. CMake offers three approaches:

  • find_package(Name) locates a library that's already installed (by the system package manager, a package manager below, or by hand) and provides imported targets such as fmt::fmt or GTest::gtest_main:

    CMAKE
    find_package(fmt CONFIG REQUIRED)
    target_link_libraries(weather PRIVATE fmt::fmt)
    
  • FetchContent downloads a dependency's source at configure time and builds it as part of your project. Convenient for small libraries and test frameworks; pin an exact tag or commit:

    CMAKE
    include(FetchContent)
    FetchContent_Declare(googletest
        GIT_REPOSITORY https://github.com/google/googletest.git
        GIT_TAG        v1.15.2)
    FetchContent_MakeAvailable(googletest)
    target_link_libraries(parser_test PRIVATE GTest::gtest_main)
    
  • A package manager that installs prebuilt or source-built libraries for your exact compiler and platform, then hands them to find_package.

vcpkg

vcpkg (from Microsoft, cross-platform) has thousands of libraries. In manifest mode you list dependencies in a vcpkg.json file next to CMakeLists.txt:

JSON
{
  "name": "weather",
  "version": "1.2.0",
  "dependencies": [ "fmt", "nlohmann-json", "gtest" ]
}

Then point CMake at vcpkg's toolchain file, and vcpkg builds the libraries automatically during configuration:

Terminal
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake

Conan

Conan (Python-based, popular in industry) describes dependencies in a conanfile.txt (or a Python conanfile.py for more control) and generates files CMake understands:

INI
[requires]
fmt/11.0.2
nlohmann_json/3.11.3

[generators]
CMakeDeps
CMakeToolchain
Terminal
conan install . --output-folder=build --build=missing
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=build/conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Release
cmake --build build

Both are good choices: vcpkg is simpler to start with and integrates tightly with Visual Studio; Conan offers binary caching servers and fine-grained control that large organizations like. Whichever you pick, your CMakeLists.txt stays the same: find_package plus target_link_libraries.

Builds differ by platform and compiler

A build system's other job is to cope with differences between compilers and platforms. CMake knows them (that's what CMAKE_CXX_COMPILER_ID and generator expressions are for), and inside the code, every compiler predefines macros that identify it:

C++ What the compiler tells your code about itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Our server reports GCC 15.2 on 64-bit Linux, with optimization on (it compiles with -O1). Note that Clang also defines __GNUC__, which is why the Clang check must come first. Keep such #if blocks rare and isolated in one place; the build system is the better home for platform choices.

Other build systems

CMake dominates, but you'll meet others:

  • Ninja: not a project format but a very fast low-level build executor. CMake and Meson generate Ninja files; prefer -G Ninja for speed.
  • Meson: a clean, Python-like syntax, fast and popular in open-source Linux projects (GNOME, systemd).
  • MSBuild: Visual Studio's native .vcxproj format, common in Windows-only codebases.
  • Bazel (and Buck2): hermetic, reproducible builds for huge monorepos with many languages, from Google and Meta.
  • xmake and build2: integrated build system plus package manager.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a project of main.cpp, a.cpp and b.cpp, only b.cpp is edited. What should a correct incremental build do?

    Only b.o is out of date, but the executable depends on b.o, so the link step must run again too.
  2. 2. A Makefile compiles with plain -c, and someone edits a header that three .cpp files include. What happens on the next make?

    Make only knows the prerequisites you list. Compiling with -MMD -MP writes dependency files that list every included header, and including them fixes this.
  3. 3. target_include_directories(core PUBLIC include) and target_link_libraries(app PRIVATE core). Does app get the include directory?

    PUBLIC means "for me and for my users". Linking core gives app its include directory automatically. PRIVATE on app only means app doesn't pass core's requirements further on.
  4. 4. What does cmake -S . -B build -G Ninja do?

    CMake is a generator. The configure step writes build files; cmake --build build (or running ninja) then does the actual compilation.
  5. 5. You need fmt and GoogleTest built for MSVC, GCC and Clang across your team. What fits best?

    Package managers build or download each library for the exact compiler and platform, and CMake consumes them with find_package and target_link_libraries.

Summary

  • A build system tracks a dependency graph and rebuilds only what's out of date, in parallel, with consistent flags.
  • A Makefile lists targets, prerequisites and tab-indented recipes; use pattern rules, $@ $< $^, and -MMD -MP so header changes trigger rebuilds.
  • CMake generates native build files from a portable CMakeLists.txt. Write modern CMake: targets plus target_* commands with PRIVATE/PUBLIC/INTERFACE.
  • Configure into a separate directory with cmake -S . -B build, choose CMAKE_BUILD_TYPE (Debug, Release, RelWithDebInfo), build with cmake --build build, test with ctest.
  • Get libraries with find_package, FetchContent, or a package manager: vcpkg (vcpkg.json) or Conan (conanfile.txt).
  • Compiler- and platform-specific choices belong in the build system; inside code, predefined macros like __GNUC__ and _WIN32 identify the environment.

Next: Compilers, Flags and Optimization, where you'll see what -O2, warnings, sanitizers and LTO actually do to your program.