user1415536
user1415536

Reputation: 266

CMake Environmental variables

While using CMake and reading tons of other CMakeLists.txt files I noticed that set(ENV{variable_name} value) is used quite often. However, e.g. here https://cliutils.gitlab.io/modern-cmake/chapters/basics/variables.html the author mentions that these variables should be avoided without any further explanation. CMake documentation stands:

This command affects only the current CMake process, not the process from which CMake was called, nor the system environment at large, nor the environment of subsequent build or test processes.

My question is, is it really that bad practice to use environmental variables in CMakeLists.txt? What pitfalls must be expected with such usage?

Upvotes: 3

Views: 3165

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 66118

Nothing bad in using environment variables in CMakeLists.txt.

For example, many FindXXX.cmake scripts actually use environment variables.

What pitfalls must be expected with such usage?

  1. After reading a path from the environment variable, transform it into cmake-style path (e.g. with file(TO_CMAKE_PATH)) before access a file at this path in CMake commands. Otherwise you could get a problem on Windows, which path separator ("\") differs from the CMake one ("/").

  2. Because setting environment variable affects only on configuration stage, this is rarely needed: better to use CMake variables instead.

    The only important exception: a toolchain file could be executed multiple times during the configuration. And setting an environment variable is the only way to store a value, calculated on the first toolchain invocation, for being usable in futher invocations. (Even CACHE variables don't work in that case).

Upvotes: 5

Related Questions