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.

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

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})

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

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