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.
There are typically two use cases (please don't misuse them for global variables):
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
In the GUI the user first starts the configuration process, then can modify any cached value and finishes with starting the build environment generation.
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.