How do I check if an environment variable is set in cmake

Knowing perfectly well what export does and how environment works in general, I’ve still got a mouthful of WTFs with this form:

IF(DEFINED $ENV{THING})

but it worked fine in this form:

IF(DEFINED ENV{THING})

Notice the $ omission.


N.B. you can quickly test this using cmake -P:

[~] cat > test-env.cmake << 'EOF'
IF(DEFINED ENV{FOOBAR})
    MESSAGE(STATUS "FOOBAR env seen: --[$ENV{FOOBAR}]--")
ELSE()
    MESSAGE(STATUS "WTF")
ENDIF()
EOF
[~]
[~] FOOBAR=test cmake -P test-env.cmake
-- FOOBAR env seen: --[test]--

The reason it behaves so weirdly, is legacy, as usual. IF used to do insane stuff in older CMake; they sort-of fixed this in CMake 3.1 — in a backward-compatible manner — with CMP0054, which you have to enable explicitly:

CMAKE_MINIMUM_REQUIRED(VERSION 3.1)
PROJECT(...)

CMAKE_POLICY(SET CMP0054 NEW) #-- fixes IF() with quoted args
CMAKE_POLICY(SET CMP0057 NEW) #-- enables IF(.. IN_LIST ..)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)