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


You can also invoke 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")

message("EnvironmentVariableName = ${EnvironmentVariableName}")



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


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

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.

Environment variable not found by cmake

I've just given your example a try and it works fine in my Ubuntu bash shell.

# export WM5_PATH=/home/user/catkin_ws/src/GeometricTools/WildMagic5/SDK
# cmake ..
-- Configuring done
-- Generating done
-- Build files have been written to: ...

So I suspect your cmake executable runs in another environment (e.g. an IDE).

To check what your CMake does see as an environment you could add the following to your CMakeLists.txt:

    COMMAND ${CMAKE_COMMAND} -E environment