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?
Use the syntax $ENV{VAR} to read environment variable VAR . To test whether an environment variable is defined, use the signature if(DEFINED ENV{<name>}) of the if() command. For general information on environment variables, see the Environment Variables section in the cmake-language(7) manual.
The type of the variable is used by the cmake-gui to control how that variable is set and displayed, but the value is always stored in the cache file as a string.
The getenv() function in C++ returns a pointer to a C string containing the value of the environment variable passed as argument. If the environment variable passed to the getenv() function is not in the environment list, it returns a null pointer.
Local Variables You access a variable by using ${} , such as ${MY_VARIABLE} . 1. CMake has the concept of scope; you can access the value of the variable after you set it as long as you are in the same scope. If you leave a function or a file in a sub directory, the variable will no longer be defined.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With