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

后端 未结 4 427
长情又很酷
长情又很酷 2020-12-07 13:46

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

$ENV{EnvironmentVariableName}

but I can not retrieve a use

4条回答
  •  离开以前
    2020-12-07 14:31

    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

提交回复
热议问题