[CMake] Checking for empty string

Rolf Eike Beer eike at sf-mail.de
Tue Oct 25 09:19:02 EDT 2011


> On Tue, Oct 25, 2011 at 6:31 AM, Rolf Eike Beer <eike at sf-mail.de> wrote:
>
>> > hi there,
>> >
>> > how do I test if a string is empty ("") or not ?
>> > IF( ${test} STREQUAL "" )
>> > gives the wrong number of arguments if ${test} is ""
>>
>> if ("${test}" STREQUAL "")
>> if (NOT test)
>>
>> What does not work (in 2.8.5) but should work according to the
>> documentation:
>>
>> if (test STREQUAL "")
>
> Ah, but this does work, and it works precisely according to the
> documentation. Unfortunately, it is complicated, and confusing to human
> beings, though...
>
> The construct:
>
>   if (test STREQUAL "")
>
> is evaluated differently according to context. The context is whether or
> not
> there is a variable defined that is named "test".
>
> If there is a variable named test, then we do variable-value comparison:
>   if (test STREQUAL "")
> is equivalent to:
>   if ("${test}" STREQUAL "")
> (It is this way for backwards compatibility with IF commands that were
> written before we even had ${test} variable expansion in the CMake
> language.
> Years ago at this point...)
>
> If there is no variable named test, then we do string literal comparison:
>   if (test STREQUAL "")
> is equivalent to:
>   if ("test" STREQUAL "")
>
> If you are intending string value comparison with variables, I always
> recommend always using double quotes and always using the form:
>   if ("${test}" STREQUAL "")
>
> because it is unambiguous, and the meaning is clearer from reading it.
>
>
> This is all illustrated by the following script:
> (run with cmake -P to see the output does NOT go to the FATAL_ERROR
> segments.....)

That's close to what I did in testing. But only close, I began with:

set(test)

> # test is not a defined variable at this point, so the following test is a
> # simple string compare between the left and right arguments, which are
> # "test" and ""
> #
> if (test STREQUAL "")
>   message(FATAL_ERROR "unexpected: the string literal 'test' is the empty
> string")
> else()
>   message("the string 'test' is not the empty string")
> endif()

And then this still tells me "test" is not the empty string. Which can be
considered expected behaviour if an empty variable is not the empty
string, but both are "NOT test". Something like QString::null() vs.
QString::empty(). You just have to know about it's suptle differences.

Eike


More information about the CMake mailing list