Skip to content
Latchkey

cmake -D: Set Cache Variables at Configure Time

cmake -D<var>=<value> writes a value into the CMake cache at configure time, controlling everything from build type to feature toggles.

Cache variables are how you steer a CMake build from the command line. In CI you set build type, install prefix, and project options with -D rather than editing files.

What it does

Each -D writes one variable into CMakeCache.txt. Built-in variables control the toolchain and layout; project-defined option() variables toggle features. Values persist in the cache, so a reconfigure keeps them unless overridden.

Common usage

Terminal
cmake -S . -B build \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_INSTALL_PREFIX=/usr/local \
  -DBUILD_TESTING=ON \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

Options

VariableWhat it does
CMAKE_BUILD_TYPEDebug, Release, RelWithDebInfo, MinSizeRel (single-config only)
CMAKE_INSTALL_PREFIXWhere cmake --install places files
CMAKE_CXX_COMPILERPath to the C++ compiler to use
CMAKE_EXPORT_COMPILE_COMMANDSEmit compile_commands.json (ON/OFF)
BUILD_SHARED_LIBSBuild shared vs static libraries
-D<var>:<type>=<value>Optionally type the value, e.g. FILEPATH, BOOL

In CI

CMAKE_BUILD_TYPE is ignored by multi-config generators (Visual Studio, Xcode); pass the config to --build --config instead. Set CMAKE_EXPORT_COMPILE_COMMANDS=ON so linters and clang-tidy have a compile database.

Common errors in CI

"CMake Warning: Manually-specified variables were not used by the project" flags a typo in a -D name or an option the project does not define. Setting CMAKE_BUILD_TYPE with a multi-config generator has no effect and yields an unexpectedly unoptimized build. A cached compiler path that no longer exists needs --fresh or a wiped build dir.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →