skip to content

CMake

CMake generates native builds for C and C++ from targets with usage requirements, and is the default answer for cross-platform builds. Interviewers check modern, target-based habits.

on this pageshow

explore

questions

page 1 of 2

In CMake, what do the Debug, Release, RelWithDebInfo and MinSizeRel build types change, and how does CMAKE_BUILD_TYPE select one?

level: juniorimportance: must knowfreq 70%

answer

  1. four standard configurations
  2. CMAKE_CXX_FLAGS_<CONFIG>
  3. NDEBUG in the release types
  4. empty is not Debug
  5. set once, at configure

basics

~20 s

Each build type adds its own flags from CMAKE_CXX_FLAGS_<CONFIG>: with GCC or Clang, Debug adds -g, Release -O3 -DNDEBUG, RelWithDebInfo -O2 -g -DNDEBUG, MinSizeRel -Os -DNDEBUG. Single-config generators take the type from CMAKE_BUILD_TYPE at configure time; left empty, none of these flags apply.

solid answer

~40 s

CMake defines four standard **configurations**, and each one owns a flag variable `CMAKE_CXX_FLAGS_<CONFIG>` (upper-case name) that is added on top of `CMAKE_CXX_FLAGS`. With GCC and Clang the defaults are `-g` for `Debug`, `-O3 -DNDEBUG` for `Release`, `-O2 -g -DNDEBUG` for `RelWithDebInfo` and `-Os -DNDEBUG` for `MinSizeRel`, so the release types also switch `assert` off. With a single-config generator such as Ninja or Makefiles you pick the type once, at configure time: `cmake -S . -B build -DCMAKE_BUILD_TYPE=Release`. If nobody sets it, it takes a toolchain-specific default, which is empty with GCC and Clang on Linux and macOS, and an empty build type is **not** Debug: it adds no configuration flags at all. Multi-config generators ignore `CMAKE_BUILD_TYPE` and choose at build time with `--config`.

code

cmake · 7 lines
cmake
cmake_minimum_required(VERSION 3.25)
project(render CXX)
message(STATUS "BT=[${CMAKE_BUILD_TYPE}]")
foreach(c DEBUG RELEASE RELWITHDEBINFO MINSIZEREL)
  message(STATUS "${c}: [${CMAKE_CXX_FLAGS_${c}}]")
endforeach()
add_executable(render main.cpp)

go deeper

for a junior

Name the four build types, pass -DCMAKE_BUILD_TYPE=Release when configuring, and know that the release types define NDEBUG.

for a middle

Explain the CMAKE_CXX_FLAGS_<CONFIG> variables, the toolchain-specific default, and why an empty build type produces neither an optimized nor a debuggable binary.

for a senior

Make the build type explicit in every script and preset, and read the real compile lines rather than trusting the name of a directory.

for a principal

Decide which configurations a team ships and tests, including any custom ones, and keep their flags defined in one place.

## What a build type is A **build type**, which CMake also calls a **configuration**, is a named set of compiler and linker flags. CMake ships four standard ones: - `Debug`: debug information, no optimization flags. - `Release`: full optimization and assertions disabled. - `RelWithDebInfo`: optimized but still debuggable. - `MinSizeRel`: optimized for size. Projects can define more, such as `Profile` or `Asan`; each configuration then needs its own flag variables. ## The flags behind each type Every configuration has a variable named `CMAKE_<LANG>_FLAGS_<CONFIG>`, where `<CONFIG>` is the configuration name in upper case. For C++ these are cache variables such as `CMAKE_CXX_FLAGS_RELEASE`, initialised from the compiler's defaults when a build tree is created. A CMake 4.4.4 configure with Apple clang, whose defaults come from CMake's GNU-family compiler module, printed: | Configuration | `CMAKE_CXX_FLAGS_<CONFIG>` with GCC or Clang | |---|---| | `Debug` | `-g` | | `Release` | `-O3 -DNDEBUG` | | `RelWithDebInfo` | `-O2 -g -DNDEBUG` | | `MinSizeRel` | `-Os -DNDEBUG` | The compile line is `CMAKE_CXX_FLAGS`, then the flags of the active configuration, then the target's own options. `-DNDEBUG` matters as much as the optimization level: it defines the `NDEBUG` macro, which makes the standard `assert` macro expand to nothing, so a release type never evaluates assertions. Other compilers get their own values, for example MSVC's `/O2` style flags. What each optimization level does to the code belongs to the material on GCC optimization levels. ## Selecting a type with a single-config generator With `Unix Makefiles` or `Ninja`, one build tree holds one configuration: ```console cmake -S . -B build-release -G Ninja -DCMAKE_BUILD_TYPE=Release cmake --build build-release ``` 1. `-DCMAKE_BUILD_TYPE=Release` stores the type in the cache when the tree is configured. 2. The `CMAKE_BUILD_TYPE` environment variable (CMake 3.22+) supplies a default only when a new tree is created without an explicit type. 3. Otherwise a **toolchain-specific default** applies: empty with GCC and Clang on Linux and macOS, `Debug` with MSVC and clang-cl on Windows, whose platform modules set `CMAKE_BUILD_TYPE_INIT` to `Debug`, and `RelWithDebInfo` for Android NDK builds. To get both Debug and Release with a single-config generator you configure two directories, such as `build-debug/` and `build-release/`. ## The empty build type The CMake build-system manual warns that an empty `CMAKE_BUILD_TYPE` is commonly mistaken for `Debug`, and it is not. With an empty type the compile line carries only `CMAKE_CXX_FLAGS` and the target's options. A Ninja build of a library with no build type and Apple clang compiled with `-std=gnu++20 -arch arm64` and nothing else: no `-O`, no `-g`, no `-DNDEBUG`. The result is unoptimized code with assertions still active, and no debug information either. Always pass a build type explicitly. ## Multi-config generators choose later Visual Studio, Xcode and `Ninja Multi-Config` generate every configuration listed in `CMAKE_CONFIGURATION_TYPES` and ignore `CMAKE_BUILD_TYPE`; you pick one with `cmake --build build --config Release` or in the IDE. Code that reads `CMAKE_BUILD_TYPE` in `if()` therefore only works for single-config generators; per-configuration settings are written with `$<CONFIG:...>` generator expressions instead. ## Inspecting and overriding the flags Because the per-configuration flags are ordinary cache variables, you can see and change them without touching the project: - `cmake -LA -N build` lists the cached variables, advanced ones included, and shows `CMAKE_CXX_FLAGS_RELEASE` with its current value; `CMakeCache.txt` holds the same. - `-DCMAKE_CXX_FLAGS_RELEASE="-O2 -DNDEBUG"` on the first configure replaces the default for that build tree, which some teams use to ship `-O2` instead of `-O3`. - A toolchain file can seed the defaults through `CMAKE_CXX_FLAGS_RELEASE_INIT` and its siblings, which initialise the cache entry the first time a tree is configured; CMake may prepend or append its own content. - `cmake --build build -v` prints the compile lines, which is the only reliable proof of which flags a configuration really used. Editing these variables with `set()` inside `CMakeLists.txt` is a common mistake: a normal variable shadows the cache entry from that directory down, so the value users see in the cache no longer matches the build. Per-target, per-configuration options belong in `target_compile_options` with a `$<CONFIG:...>` condition instead. ## Case and comparisons Configuration names are case-insensitive where CMake uses them internally, so `$<CONFIG:Debug>` also matches `DEBUG`. Plain string comparisons in `if()` are case-sensitive, and `if(CMAKE_BUILD_TYPE STREQUAL DEBUG)` is false for `Debug`. The flag variables always use the upper-case name: `CMAKE_CXX_FLAGS_RELWITHDEBINFO`, never `CMAKE_CXX_FLAGS_RelWithDebInfo`.

  • Why do release binaries from CMake ignore assert() calls even though nobody wrote -DNDEBUG?
    The default `CMAKE_CXX_FLAGS_RELEASE`, `CMAKE_CXX_FLAGS_RELWITHDEBINFO` and `CMAKE_CXX_FLAGS_MINSIZEREL` for GCC and Clang contain `-DNDEBUG`, and the standard `assert` macro expands to nothing when `NDEBUG` is defined. Only `Debug`, and an empty build type, leave assertions active. A project that wants checks in release builds needs its own check macro rather than `assert`.
  • How do you add a custom Profile build type to a single-config CMake build?
    Pass `-DCMAKE_BUILD_TYPE=Profile` and define the matching flag variables, typically as cache entries: `CMAKE_CXX_FLAGS_PROFILE`, and the linker variables such as `CMAKE_EXE_LINKER_FLAGS_PROFILE` if needed. Without them the configuration exists but adds no flags. For multi-config generators, also add `Profile` to `CMAKE_CONFIGURATION_TYPES`.

  • An empty CMAKE_BUILD_TYPE means CMake builds Debug
  • RelWithDebInfo uses the same flags as Release plus -g
  • Release builds keep assert() checks because NDEBUG must be defined by hand
  • You switch a Ninja build directory from Debug to Release with cmake --build --config Release
  • The flag variable for RelWithDebInfo is CMAKE_CXX_FLAGS_RelWithDebInfo
open as a page

In CMake, what do enable_testing() and add_test() do, and how does ctest find and run the tests they register?

level: juniorimportance: must knowfreq 60%

basics

~20 s

enable_testing() makes CMake write CTestTestfile.cmake files into the build tree, and add_test(NAME ... COMMAND ...) records a command in them. ctest, run in the top-level build directory, reads those files and runs each command; exit code 0 passes.

open as a page

In CMake, why link the imported target ZLIB::ZLIB after find_package(ZLIB) instead of using ZLIB_INCLUDE_DIRS and ZLIB_LIBRARIES?

level: juniorimportance: must knowfreq 60%

basics

~20 s

An imported target bundles the include directories, link file and other usage requirements in one name, so a single target_link_libraries call applies them all, CMake errors on a misspelled name, and per-configuration library paths are chosen for you.

open as a page

In CMake, what does a generator do, how do you choose one with -G, and why does a build directory keep only one?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A CMake generator writes the native build system: Makefiles, build.ninja, a Visual Studio solution or an Xcode project. You pick it with -G when a build directory is first configured; the choice is recorded there, so another generator needs another or a fresh directory.

open as a page

In CMake, what do the PRIVATE, PUBLIC and INTERFACE keywords mean in target_link_libraries and target_include_directories?

level: juniorimportance: must knowfreq 82%

basics

~20 s

They decide who receives a setting. PRIVATE applies it only when building the target itself, INTERFACE only to targets that link to it, and PUBLIC to both, so a dependency that a library's public headers include must be PUBLIC.

open as a page

In CMake, what does passing -DNAME=VALUE to the cmake command do, and why does the value persist on later runs?

level: juniorimportance: must knowfreq 64%

basics

~20 s

cmake -DNAME=VALUE creates or updates a cache entry in the build tree's CMakeCache.txt. The cache survives between runs, so later configures of that build directory keep the value until someone changes or removes the entry.

open as a page

In CMake, how do CMAKE_CXX_STANDARD, CMAKE_CXX_STANDARD_REQUIRED and target_compile_features differ when a project needs C++20?

level: middleimportance: must knowfreq 65%

basics

~20 s

CMAKE_CXX_STANDARD sets the default CXX_STANDARD of targets created afterwards; without CMAKE_CXX_STANDARD_REQUIRED it may decay to an older standard. target_compile_features(lib PUBLIC cxx_std_20) is a per-target minimum that also propagates to consumers and fails if the compiler cannot meet it.

open as a page

Which ctest options run a CMake test suite in parallel, select tests by name or label, and show the output of failures?

level: middleimportance: must knowfreq 55%

basics

~20 s

ctest -j N runs up to N tests at once; -R and -E select or exclude tests by name regex, -L and -LE by label regex; --output-on-failure prints failing tests' captured output; --rerun-failed repeats the last run's failures.

open as a page

In CMake, how do FetchContent_Declare and FetchContent_MakeAvailable bring in a dependency, and how can an installed copy win instead?

level: middleimportance: must knowfreq 55%

basics

~10 s

FetchContent_Declare records where a dependency's source comes from; FetchContent_MakeAvailable downloads it at configure time and adds it with add_subdirectory. With FIND_PACKAGE_ARGS it first tries find_package and fetches only when that fails.

open as a page

In CMake, what is the difference between find_package module mode and config mode, and how does it choose between them?

level: middleimportance: must knowfreq 65%

basics

~20 s

Module mode loads a Find<Name>.cmake script written outside the package that searches for its files; config mode loads the <Name>Config.cmake file the package installed. The basic signature tries module mode first, then config mode; CONFIG or MODULE forces one.

open as a page

In CMake, what does cmake_minimum_required(VERSION 3.25...4.4) actually set, and what does CMake 4 do with a minimum below 3.5?

level: middleimportance: must knowfreq 55%

basics

~20 s

It refuses CMake releases older than 3.25 and sets the policy version to 4.4, so every policy introduced up to 4.4 uses NEW behaviour. CMake 4 rejects a policy version below 3.5 with an error unless CMAKE_POLICY_VERSION_MINIMUM raises it.

open as a page

In CMake, why is target_compile_options preferred over directory-wide commands such as add_compile_options and include_directories?

level: middleimportance: must knowfreq 55%

basics

~20 s

Directory-wide commands affect every target in a directory and its subdirectories, depending on call order, and never reach consumers in other directories. target_* commands state each target's requirements explicitly and let PUBLIC and INTERFACE requirements propagate to whoever links it.

open as a page

In CMake, why does changing an option() default from ON to OFF in CMakeLists.txt not affect an existing build directory?

level: middleimportance: must knowfreq 62%

basics

~20 s

option() and set(... CACHE ...) only write an entry that does not exist yet. An existing build tree already holds the old value in CMakeCache.txt, so the new default is ignored until that entry is removed or overwritten.

open as a page

In CMake, what is a generator expression such as $<CONFIG>, and why does message() print it unevaluated?

level: juniorimportance: should knowfreq 50%

basics

~20 s

A generator expression is a $<...> placeholder that CMake evaluates while generating the build system, separately for each configuration and target. message() runs earlier, while CMakeLists.txt is read, so it prints the raw text; file(GENERATE) shows real values.

open as a page

In CMake, what do install(TARGETS) rules and GNUInstallDirs do, and how does cmake --install place a library and its headers?

level: juniorimportance: should knowfreq 45%

basics

~20 s

install() rules record what to copy where, relative to an install prefix; cmake --install build executes them. GNUInstallDirs supplies standard relative destinations such as CMAKE_INSTALL_LIBDIR and CMAKE_INSTALL_INCLUDEDIR, and headers need their own install(DIRECTORY), install(FILES) or file-set rule.

open as a page

In CMake, what problem do CMakePresets.json and CMakeUserPresets.json solve, and which one belongs in version control?

level: juniorimportance: should knowfreq 45%

basics

~20 s

They record named configure, build and test settings, such as generator, build directory and cache variables, so everyone runs cmake --preset <name> instead of retyping -D flags. CMakePresets.json is committed for the project; CMakeUserPresets.json holds personal presets and stays out of version control.

open as a page

In CMake, how does configure_file turn a version.h.in template into a C++ header that carries the project version?

level: juniorimportance: should knowfreq 55%

basics

~20 s

configure_file copies the template at configure time, replacing @VAR@ and ${VAR} with CMake variable values and turning #cmakedefine lines into #define or #undef. Put the output in the build tree and add that directory to the target's include path.

open as a page

In CMake, how do you add warning flags for GCC and Clang only with a generator expression, and which mistakes make it silently fail?

level: middleimportance: should knowfreq 45%

basics

~10 s

Wrap the flags in a compiler-id test: "$<$<CXX_COMPILER_ID:GNU,Clang,AppleClang>:-Wall;-Wextra>". Forgetting AppleClang skips Apple clang, and a space inside the quoted expression passes "-Wall -Wextra" as one bogus flag.

open as a page

In CMake, why can't if(CMAKE_BUILD_TYPE STREQUAL "Debug") select Debug-only definitions under a multi-config generator, and what replaces it?

level: middleimportance: should knowfreq 52%

basics

~10 s

Multi-config generators such as Visual Studio, Xcode and Ninja Multi-Config generate every configuration from one configure run, so an if() runs once and cannot differ per configuration. $<$CONFIG:Debug:IMGPROC_CHECKS> is evaluated separately for each configuration.

open as a page

In CMake, how does a single-config generator such as Ninja differ from multi-config generators like Ninja Multi-Config, Visual Studio or Xcode?

level: middleimportance: should knowfreq 50%

basics

~20 s

A single-config generator builds one configuration per build tree, fixed at configure time. A multi-config generator writes every configuration in CMAKE_CONFIGURATION_TYPES into one tree, and the configuration is picked at build time with --config or in the IDE.

open as a page

In CMake, what must the geom project install so another team can write find_package(geom 2.1) and link geom::geom?

level: middleimportance: should knowfreq 50%

basics

~10 s

Install geom into an export set, install that set with install(EXPORT ... NAMESPACE geom::), and install geomConfig.cmake, which includes the generated targets file, plus geomConfigVersion.cmake from write_basic_package_version_file, all under lib/cmake/geom.

open as a page

In CMakePresets.json, how do hidden presets, inherits, and build, test and workflow presets combine into one repeatable configure-build-test flow?

level: middleimportance: should knowfreq 40%

basics

~20 s

Shared settings go into a hidden configure preset that concrete presets inherit; build and test presets point at a configure preset and reuse its build directory; a workflow preset chains configure, build, test and package steps so cmake --workflow runs them all.

open as a page

In CMake, why can if(${BACKEND} STREQUAL "metal") misbehave or fail when if(BACKEND STREQUAL "metal") works?

level: middleimportance: should knowfreq 48%

basics

~20 s

${BACKEND} is expanded before if() runs, and if() then treats an unquoted word as a variable name and dereferences it again. A value that names another variable gives a wrong answer; an empty value leaves STREQUAL without a left operand.

open as a page

In CMake, how does cmake_parse_arguments give a helper like engine_add_library(core TYPE STATIC SOURCES a.cpp) keyword arguments?

level: middleimportance: should knowfreq 44%

basics

~10 s

cmake_parse_arguments sorts the call's arguments into option, one-value and multi-value keywords and sets prefix_KEYWORD variables. Leftovers go to prefix_UNPARSED_ARGUMENTS and keywords given no value to prefix_KEYWORDS_MISSING_VALUES, which the helper should reject.

open as a page

In CMake, how do the STATIC, SHARED, MODULE, OBJECT and INTERFACE library kinds of add_library differ?

level: middleimportance: should knowfreq 55%

basics

~20 s

STATIC archives object files for linking into consumers, SHARED builds a library loaded at run time, MODULE builds a plugin nothing may link, OBJECT compiles sources without archiving them, and INTERFACE builds nothing and only carries usage requirements.

open as a page

In CMake, why is a variable set in a subdirectory invisible to the parent after add_subdirectory, and what does PARENT_SCOPE change?

level: middleimportance: should knowfreq 52%

basics

~20 s

add_subdirectory gives the child a new directory scope initialised with a copy of the parent's variables, so the child's set() calls stay local. set(NAME value PARENT_SCOPE) writes the parent's binding instead, leaving the child's own copy unchanged.

open as a page

In CMake, why can cmake -DRENDER_BACKEND=metal seem ignored when CMakeLists.txt also calls set(RENDER_BACKEND vulkan)?

level: middleimportance: should knowfreq 50%

basics

~10 s

set(RENDER_BACKEND vulkan) creates a normal variable, and ${RENDER_BACKEND} looks up normal variables before the cache. The -D value still sits in the cache, but the normal binding hides it.

open as a page

A CMake project's shipped release binary turns out unoptimized and still runs its assert() checks; how do you find whether the build type or the generator caused it, and fix it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

Check the compile lines with cmake --build -v: no -O and no -DNDEBUG means no Release flags were used. Either CMAKE_BUILD_TYPE was never set on a single-config generator, or a multi-config generator ignored it and cmake --build without --config built Debug.

open as a page

Tests in a CMake suite pass with plain ctest but fail under ctest -j 8 because several share one scratch database; which test properties make them safe to parallelize?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Give the database tests one RESOURCE_LOCK so ctest never runs them together, and use FIXTURES_SETUP, FIXTURES_REQUIRED and FIXTURES_CLEANUP so creating and deleting it run first and last. DEPENDS only orders tests; RUN_SERIAL is the blunt fallback.

open as a page

After an internal CMake package was reinstalled to a new prefix and CMAKE_PREFIX_PATH updated, reconfiguring still uses the old copy; why, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Config mode stored the old directory in the Ledger_DIR cache entry, and find_package reuses a cached directory that still holds a valid config file without searching again. Remove that entry with -U Ledger_DIR or reconfigure with --fresh.

open as a page

showing 1–30 of 45