TExcelTAD
Home › Modern CMake (with CTest & CPack) › Options & Cache Variables

Options & Cache Variables

A project usually has knobs: build the tests or not, use a feature or not, where to find a tool. CMake stores them in the cache (CMakeCache.txt in the build directory), so a choice made once is remembered on every later configure.

option(): boolean switches

cmake
option(SHAPES_BUILD_TESTS "Build the unit tests" ON)
option(SHAPES_WITH_SIMD "Use SIMD code paths" OFF)

option() creates a BOOL cache entry only if it doesn't exist yet. The user overrides it on the command line, in a preset, or interactively in ccmake/cmake-gui:

bash · try it yourself
mkdir -p opts && cd opts
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Shapes LANGUAGES NONE)
option(SHAPES_BUILD_TESTS "Build the unit tests" ON)
option(SHAPES_WITH_SIMD "Use SIMD code paths" OFF)
set(SHAPES_BACKEND "opengl" CACHE STRING "Rendering backend")
set_property(CACHE SHAPES_BACKEND PROPERTY STRINGS opengl vulkan metal)
set(allowed_backends opengl vulkan metal)
if(NOT SHAPES_BACKEND IN_LIST allowed_backends)        # IN_LIST takes a variable name
  message(FATAL_ERROR "SHAPES_BACKEND must be opengl, vulkan or metal, not '${SHAPES_BACKEND}'")
endif()
message("tests=${SHAPES_BUILD_TESTS} simd=${SHAPES_WITH_SIMD} backend=${SHAPES_BACKEND}")
CM
echo "--- defaults";             cmake -S . -B build --log-level=NOTICE 2>&1 | grep -v "^--"
echo "--- override";             cmake -S . -B build -DSHAPES_WITH_SIMD=ON -DSHAPES_BACKEND=vulkan 2>&1 | grep -v "^--"
echo "--- remembered";           cmake -S . -B build 2>&1 | grep -v "^--"
echo "--- list the cache";       cmake -L -N build | grep SHAPES
echo "--- with help strings";    cmake -LH -N build | grep -B1 SHAPES_BACKEND
echo "--- bad value";            cmake -S . -B build -DSHAPES_BACKEND=dx12 2>&1 | grep -v "^--" | sed -n 1,2p
--- defaults
tests=ON simd=OFF backend=opengl
--- override
tests=ON simd=ON backend=vulkan
--- remembered
tests=ON simd=ON backend=vulkan
--- list the cache
SHAPES_BACKEND:STRING=vulkan
SHAPES_BUILD_TESTS:BOOL=ON
SHAPES_WITH_SIMD:BOOL=ON
--- with help strings
// Rendering backend
SHAPES_BACKEND:STRING=vulkan
--- bad value
CMake Error at CMakeLists.txt:9 (message):
  SHAPES_BACKEND must be opengl, vulkan or metal, not 'dx12'
  • -L lists non-advanced cache entries, -LA all of them, -LH with help strings; -N reads the cache without configuring.
  • STRINGS gives GUIs a drop-down; it doesn't validate anything, so the project checks the value itself.
  • Prefix every option with the project name (SHAPES_…). When your project is used via add_subdirectory or FetchContent, a generic BUILD_TESTS would collide with everyone else's.

Cache variables vs normal variables

set(VAR value) creates a normal variable; set(VAR value CACHE TYPE "doc") a cache entry. They live in separate namespaces, and a normal variable with the same name hides the cache entry. The rules that trip people up:

bash · try it yourself
mkdir -p shadow && cd shadow
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Shadow LANGUAGES NONE)

set(LEVEL 3 CACHE STRING "Optimisation level")
message("1. LEVEL = ${LEVEL}")            # the cache value

set(LEVEL 5)                              # a normal variable now hides it
message("2. LEVEL = ${LEVEL}  (cache still says $CACHE{LEVEL})")

set(LEVEL 9 CACHE STRING "Optimisation level")   # cache entry exists: no effect
message("3. LEVEL = ${LEVEL}  (cache still says $CACHE{LEVEL})")

set(LEVEL 9 CACHE STRING "Optimisation level" FORCE)   # FORCE overwrites the user's choice!
message("4. LEVEL = ${LEVEL}  (cache now says $CACHE{LEVEL})")
unset(LEVEL)                              # remove the normal variable
message("5. LEVEL = ${LEVEL}")
CM
cmake -S . -B build --log-level=NOTICE -DLEVEL=1 2>&1 | grep -v '^--'
1. LEVEL = 1
2. LEVEL = 5  (cache still says 1)
3. LEVEL = 5  (cache still says 1)
4. LEVEL = 5  (cache now says 9)
5. LEVEL = 9
  • The user's -DLEVEL=1 wins over the set(… CACHE …) default, because the entry already existed.
  • $CACHE{LEVEL} reads the cache entry directly, ignoring a normal variable.
  • FORCE throws away the user's choice; reserve it for values the project computes, never for user options.

option() and normal variables (policy CMP0077)

A parent project often wants to configure a subproject's options: set(FMT_TEST OFF) before add_subdirectory(fmt). With policy CMP0077 set to NEW (any cmake_minimum_required ≥ 3.13), option() does nothing when a normal variable of that name already exists, so the parent's set() wins. That is what makes the pattern work with FetchContent too.

Dependent options

cmake_dependent_option makes an option available only when another condition holds:

cmake
include(CMakeDependentOption)
cmake_dependent_option(SHAPES_BUILD_GPU_TESTS "Run GPU tests" ON
                       "SHAPES_BUILD_TESTS;NOT APPLE" OFF)

If tests are off (or on macOS), SHAPES_BUILD_GPU_TESTS is forced to OFF and hidden.

Removing and resetting

Command Effect
cmake -U 'SHAPES_*' build remove matching cache entries (they get their defaults on the next configure)
cmake --fresh -S . -B build discard the whole cache
edit CMakeCache.txt works, but ccmake build (terminal UI) or cmake-gui is safer

Test yourself

option(FOO "doc" ON) and the user configured with -DFOO=OFF earlier. What is FOO now?

  1. ON
  2. OFF: option() only creates the entry if it doesn't exist
  3. Undefined
  4. Both

What does set(X 5 CACHE STRING "" FORCE) do to a value the user passed with -DX=2?

  1. Keeps 2
  2. Overwrites it with 5 on every configure
  3. Creates a second variable
  4. Errors out

Why prefix options with the project name (e.g. SHAPES_BUILD_TESTS)?

  1. CMake requires it
  2. When the project is embedded in a bigger build, a generic name like BUILD_TESTS would collide with other projects' options
  3. For alphabetical sorting
  4. Prefixes enable FORCE