if (var STREQUAL value) and value without “” –> no warning

I just realised that I have a lot of CMake code where the intention is to compare a variable with a value, but the value has no ““ around itself. This work as long as there is no variable with the same name, since then the value is kind of “implicitly quoted”. An example (not the most troubling for me, but easy to demonstrate):

if (CMAKE_CXX_COMPILER_ID STREQUAL Clang)

I will not have a variable named “Clang”, but if I had, the if-statement would turn out differently. I have several other cases where I would have liked if CMake could warn me about the lack of ““ around a value.

Just to investigate this, I made a small change to the function cmConditionEvaluator::GetVariableOrString() in the CMake source in file “cmConditionEvaluator.cxx”. Now it gives me warnings if an “unquoted string” is interpreted as a string. I find several cases that I want to fix, to make the code clearer and avoid the risk of accidental name collision with an unrelated variable.

I also noted that the “standard library” of CMake is not clean with my warning, so it perhaps too agressive.

I searched for an existing warning about this, but could not find any. Now I just want to know if I have interpreted the situation correctly, and that I have not missed some other way of being warned.

Johan Holmberg

There is a long history behind why the if() command behaves that way, including policies that changed behavior. The documentation for the if() command shows the “it’s a variable name if such a variable exists, otherwise it is treated as a string” like this:

if(<variable|string> EQUAL <variable|string>)

The behavior is deliberate and can’t really be changed, given the huge amount of users’ project code that would have to be updated. It’s an unfortunate wrinkle in the way if() works (and while(), which has the same rules). It is up to the project/developer to make sure they use the right form when using if(). Normally, that boils down to quoting values if you are not absolutely certain about whether there is or is not a variable by that name at the point of the statement.