cmake – Variables and Properties – Variables and the Global Variables Cache

Mostly you will use "normal variables":

set(VAR TRUE)
set(VAR "main.cpp")
set(VAR1 ${VAR2})

But CMake does also know global "cached variables" (persisted in CMakeCache.txt). And if normal and cached variables of the same name exist in the current scope, normal variables do hide the cached ones:

cmake_minimum_required(VERSION 2.4)
project(VariablesTest)

set(VAR "CACHED-init" CACHE STRING "A test")
message("VAR = ${VAR}")

set(VAR "NORMAL")
message("VAR = ${VAR}")

set(VAR "CACHED" CACHE STRING "A test" FORCE)
message("VAR = ${VAR}")

First Run’s Output

VAR = CACHED-init
VAR = NORMAL
VAR = CACHED

Second Run’s Output

VAR = CACHED
VAR = NORMAL
VAR = CACHED

Note: The FORCE option does also unset/remove the normal variable from the current scope.

Use Cases for Cached Variables

There are typically two use cases (please don’t misuse them for global variables):

  1. An value in your code should be modifiable from your project’s user e.g. with the cmakegui, ccmake or with cmake -D ... option:

    CMakeLists.txt / MyToolchain.cmake

    set(LIB_A_PATH "/some/default/path" CACHE PATH "Path to lib A")
    

    Command Line

    $ cmake -D LIB_A_PATH:PATH="/some/other/path" ..
    

    This does pre-set this value in the cache and the above line will not modify it.

    CMake GUI

    enter image description here

    In the GUI the user first starts the configuration process, then can modify any cached value and finishes with starting the build environment generation.

  1. Additionally CMake does cache search/test/compiler identification results (so it does not need to do it again whenever re-running the configuration/generation steps)

    find_path(LIB_A_PATH libA.a PATHS "/some/default/path")
    

    Here LIB_A_PATH is created as a cached variable.

if you want to reproduce, please indicate the source:
cmake – Variables and Properties – Variables and the Global Variables Cache - CodeDay