How to retrieve a user environment variable in CMake (Windows) How to retrieve a user environment variable in CMake (Windows) windows windows

How to retrieve a user environment variable in CMake (Windows)


Getting variables into your CMake script

You can pass a variable on the line with the cmake invocation:

FOO=1 cmake

or by exporting a variable in BASH:

export FOO=1

Then you can pick it up in a cmake script using:

$ENV{FOO}


You can also invoke itself to do this in a cross-platform way:

cmake -E env EnvironmentVariableName="Hello World" cmake ..

env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...

Run command in a modified environment.


Just be aware that this may only work the first time. If CMake re-configures with one of the consecutive builds (you just call e.g. make, one CMakeLists.txt was changed and CMake runs through the generation process again), the user defined environment variable may not be there anymore (in comparison to system wide environment variables).

So I transfer those user defined environment variables in my projects into a CMake cached variable:

cmake_minimum_required(VERSION 2.6)project(PrintEnv NONE)if (NOT "$ENV{EnvironmentVariableName}" STREQUAL "")    set(EnvironmentVariableName "$ENV{EnvironmentVariableName}" CACHE INTERNAL "Copied from environment variable")endif()message("EnvironmentVariableName = ${EnvironmentVariableName}")

Reference


You need to have your variables exported. So for example in Linux:

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.