Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 239
Lars Bilke Avatar asked Mar 27 '09 15:03

Lars Bilke


People also ask

How do I see environment variables in Cmake?

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.

Where are Cmake variables stored?

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.

How do you read an environment variable in C++?

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.

What is ${} in Cmake?

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.


2 Answers

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} 
like image 167
Cameron Lowell Palmer Avatar answered Sep 21 '22 13:09

Cameron Lowell Palmer


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

  • CMake - Command Line Tool Mode
like image 23
Florian Avatar answered Sep 22 '22 13:09

Florian