Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare the value of an environment variable in CMakeLists.txt

Tags:

cmake

How can I compare the value of an environment variable in CMakeLists.txt?

echo $CXX

/usr/local/bin/clang++

So, CXX is properly set in my /etc/profile. Then, in CMakeLists.txt I put:

message(status "CXX is " ENV{CXX})
if(DEFINED ENV{CXX})
    message(status "CXX is defined and it is " ENV{CXX})
    if(ENV{CXX} STREQUAL "/usr/local/bin/clang++")
        message(status "which = /usr/local/bin/clang++")
    endif()
else()
    message(status "CXX is undefined")
endif()

And it outputs

CXX is ENV{CXX}
CXX is defined and it ENV{CXX}

I want to modify this so it outputs

CXX is /usr/local/bin/clang++
CXX is defined and it is /usr/local/bin/clang++
which = /usr/local/bin/clang++

... And, as a side note, do I need to test if it's defined, or can I just jump straight to STREQUAL?

... And what's the difference between EQUAL and STREQUAL?

like image 862
user1902689 Avatar asked Oct 14 '25 09:10

user1902689


1 Answers

Re-written to work as intended:

message(status "CXX is " $ENV{CXX})
if(DEFINED ENV{CXX})
    message(status "CXX is defined and it is " $ENV{CXX})
    if("$ENV{CXX}" STREQUAL "/usr/local/bin/clang++")
        message(status "which = /usr/local/bin/clang++")
    endif()
else()
    message(status "CXX is undefined")
endif()

But the safer way to do it is as follows, because a variable in a string with a $ that contains the value of another variable's name will be substituted for that other variable, rather than the string. (i.e. if variable X is "foo", and variable Y is "X", "${Y}" might intended to be evaluated as "X", but since that variable name exists, it's actually evaluated as "foo")

message(status "CXX is " $ENV{CXX})
if(DEFINED ENV{CXX})
    message(status "CXX is defined and it is " $ENV{CXX})
    if($ENV{CXX} MATCHES "/usr/local/bin/clang++")
        message(status "which = /usr/local/bin/clang++")
    endif()
else()
    message(status "CXX is undefined")
endif()

NOTE:

if(NOT...MATCHES...)

does not work. You can have an empty if, so you have to write:

if(...MATCHES...)
else()
like image 180
user1902689 Avatar answered Oct 17 '25 02:10

user1902689