Skip to content

CMake: do not expand variables beforehand

Adriaan de Groot requested to merge work/adridg/cmake-if-variables into master

In general, variables in if() commands should not be expanded "by hand" before use, because substitution occurs before the if() command is parsed: in practice that means that a command like

if(${A} STREQUAL "A")

can expand to (depending on the value of A being empty, "B" or "A")

if( STREQUAL "A")
if(B STREQUAL "A")
if(A STREQUAL "A")

Then the if() command is processed, leading to:

  • a syntax error
  • comparing the value of variable B against string "A"
  • comparing the value of variable A (it's "A" because that is what ${A} expanded to) against string "A"

This is explained in section Variable Expansion of the documentation of the if() command, but keeps tripping people up.

Merge request reports