CMake if environment variable conditions

CMake’s distinct syntax and behavior mean that using variables can have distinct behavior from other languages. Using environment variables is one such case where CMake has surprising behavior. One surprising behavior is using environment variables in if() stanzas. It’s possible to check if an environment variables is defined directly in CMake, but checking the value of the environment variable must be done indirectly via a CMake internal variable. An example of this is using environment variable “CI” to detect if CMake is running on a CI or not.

if(DEFINED ENV{CI})
  message(STATUS "CI value: $ENV{CI}")
endif()

The syntax above is valid. However, to actually use an environment variable in a CMake if() statement, an internal variable is necessary like:

set(CI $ENV{CI})

if(CI)
  message(STATUS "Skipping test since CI: ${CI}")
endif()

You can verify the behavior by making file “foo.cmake” and running it with cmake -P foo.cmake