Teddy
Teddy

Reputation: 1022

Setting environment variable in cmake

I am trying to move from an own written tool to cmake for Windows to simplify our build environment.

We have a tool in the build process that requires to have set environment variables. I would like to set them with cmake but don't know how. What I have tried:

set(ENV{MYENVVAR} "My-Content")

I would expect that I can read this environment variable again with

message($ENV{MYENVVAR})

But this does not work. Even setting a variable before invoking cmake (instead of setting it in cmake) does not help, I cant read the variable in cmake.

What do I do wrong?

Edit:

Upvotes: 1

Views: 9307

Answers (1)

Alex Reinking
Alex Reinking

Reputation: 20026

You're going to need to produce a minimal, reproducible example. Here's my best attempt based on your question and unfortunately, the best I can say is "works for me":

alex@alex-ubuntu:~$ export MYENVVAR=FooBarBaz
alex@alex-ubuntu:~$ cat test.cmake 
cmake_minimum_required(VERSION 3.20)

message($ENV{MYENVVAR})

set(ENV{MYENVVAR} "My-Content")
message($ENV{MYENVVAR})

alex@alex-ubuntu:~$ cmake -P test.cmake 
FooBarBaz
My-Content
alex@alex-ubuntu:~$ echo $MYENVVAR 
FooBarBaz

So CMake can both read the environment variable and write to it in-process, but it does not affect the controlling process's (in this case bash; in your case cmd.exe) environment.

Upvotes: 2

Related Questions