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

WindowsEnvironment VariablesCmake

Windows Problem Overview


I know how to retrieve a normal machine wide environment variable in CMAKE using

$ENV{EnvironmentVariableName}

but I can not retrieve a user specific environment variable. Is it possible and how?

Windows Solutions


Solution 1 - 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}

Solution 2 - Windows

You can also invoke [tag:cmake] 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

Solution 3 - Windows

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

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.

Solution 4 - Windows

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLars BilkeView Question on Stackoverflow
Solution 1 - WindowsCameron Lowell PalmerView Answer on Stackoverflow
Solution 2 - WindowsFlorianView Answer on Stackoverflow
Solution 3 - WindowsP51DAceView Answer on Stackoverflow
Solution 4 - WindowsMark LakataView Answer on Stackoverflow