Checking for empty string doesn't work as expected

Hi,

I’ve faced w/ contr-intuitive behavior when trying to check for empty string:

cmake_policy(VERSION 3.20)
message(STATUS "ENABLE_LIBCXX=`${ENABLE_LIBCXX}`")
if(NOT ENABLE_LIBCXX STREQUAL "")
    list(APPEND _extra_args "-DENABLE_LIBCXX=${ENABLE_LIBCXX}")
endif()
message(STATUS "_extra_args=`${_extra_args}`")

which results in the following output:

$ cmake -P check-string.cmake
-- ENABLE_LIBCXX=``
-- _extra_args=`-DENABLE_LIBCXX=`

I can’t understand how if condition could be passed with undefined/empty value of ENABLE_LIBCXX??

$ cmake --version | head -n1
cmake version 3.20.5

Looks like ENABLE_LIBCXX interpreted as string, not as a variable name (even being unquoted)… ???

See this: https://cmake.org/cmake/help/latest/command/if.html#variable-expansion

What it means is that the unquoted value is first checked for being a DEFINED VARIABLE, and if yes, then expanded. Your ENABLE_LIBCXX is not a defined variable, so it’s treated as a string.

Yes, this is a long-standing pothole. Your check should be if (DEFINED ENABLE_LIBCXX AND NOT ENABLE_LIBCXX STREQUAL "")

1 Like

Using

if(NOT "${ENABLE_LIBCXX}" STREQUAL "")

should also work as expected.

1 Like