Search code examples
c++unixcmakeenvironment-variablescmake-language

How to set environment variables in CMake so that they can be visible at build time?


On macOS 12, I tried to set some environment variables in CMakeLists.txt file like this.

# Add environment variables
set(ENV{VK_ICD_FILENAMES} /Users/username/VulkanSDK/macOS/share/vulkan/icd.d/MoltenVK_icd.json)
set(ENV{VK_LAYER_PATH} /Users/username/VulkanSDK/macOS/share/vulkan/explicit_layer.d)

But I quickly realize those environment variables only affects the current CMake instance. Basically, if I use message() in the same CMakeLists.txt file, CMake can print out the exact same value as I set. However, during build time, those variables do not exist and can't guide build phase.

My current solution is to generate Xcode project file and add those environment variables manually in Edit Scheme. But I want to learn CMake and do all the configurations in CMake. My question is if there is any way I can set environment variables in CMakeLists.txt file so that they at least persist during build phase?


Solution

  • Maybe what you want is CMAKE_XCODE_ATTRIBUTE_<an-attribute>

    https://cmake.org/cmake/help/latest/variable/CMAKE_XCODE_ATTRIBUTE_an-attribute.html