skip to content

In CMake, why can if(${BACKEND} STREQUAL "metal") misbehave or fail when if(BACKEND STREQUAL "metal") works?

level: middleimportance: should knowfreq 48%

answer

  1. two rounds of expansion
  2. ${} runs before if() sees anything
  3. if() looks up bare words as variables
  4. empty value leaves no operand
  5. quoted arguments are never re-read

basics

~20 s

${BACKEND} is expanded before if() runs, and if() then treats an unquoted word as a variable name and dereferences it again. A value that names another variable gives a wrong answer; an empty value leaves STREQUAL without a left operand.

solid answer

~40 s

`if()` predates the `${}` syntax, so it dereferences on its own: for `STREQUAL`, `EQUAL`, `MATCHES` and the other comparisons, an unquoted argument that names a defined variable is replaced by its value. Writing `${BACKEND}` adds a second, earlier expansion. If `BACKEND` is `vulkan` and some variable named `vulkan` exists, `if()` compares that variable's value instead. If `BACKEND` is empty, the argument disappears and CMake stops with `Unknown arguments specified`. Write the variable name bare, `if(BACKEND STREQUAL "metal")`, or quote the expansion, `if("${BACKEND}" STREQUAL "metal")`. Since CMake 3.1 a quoted argument is never dereferenced again (policy CMP0054), and CMake 4.0 removed that policy's OLD behaviour, so in CMake 4 quoting is always safe.

code

cmake · 19 lines
cmake
cmake_minimum_required(VERSION 3.25)
project(render NONE)

set(BACKEND "vulkan")
set(vulkan "metal")          # some other variable happens to be named vulkan

if(${BACKEND} STREQUAL "metal")
  message(STATUS "A: TRUE (vulkan was dereferenced again)")
endif()
if(BACKEND STREQUAL "vulkan")
  message(STATUS "B: TRUE")
endif()
if("${BACKEND}" STREQUAL "vulkan")
  message(STATUS "C: TRUE")
endif()

set(EMPTY_VAR "")
if(${EMPTY_VAR} STREQUAL "")   # configure error: no left operand
endif()

go deeper

for a junior

Recall that inside if() you write variable names without ${} in comparisons, or quote the expansion.

for a middle

Explain the two expansion rounds, why a value naming another variable is compared wrongly, and why an empty value removes an operand.

for a senior

Diagnose 'Unknown arguments specified' and order-dependent if() results quickly, and know CMP0054's history up to its removal in CMake 4.0.

for a principal

Adopt a lint rule or review checklist for if() spelling so a whole codebase stops depending on which variables happen to exist.

## Two expansions, not one Every CMake command receives its arguments **after** ordinary variable references have been expanded. `if()` is special because, as its documentation says, it was written before the `${}` syntax existed and evaluates variables named by its arguments **itself**. So a condition can be expanded twice: 1. The CMake language replaces `${BACKEND}` with its value before `if()` is called. 2. `if()` then looks at each unquoted argument where its syntax accepts `<variable|string>` and, if a variable of that name is defined, uses that variable's value. For `STREQUAL`, `STRLESS`, `EQUAL`, `LESS`, `VERSION_LESS` and their relatives, both sides are checked this way; for `MATCHES` and `IN_LIST`, the left side is. ## Failure one: a value that is also a variable name ```cmake set(BACKEND "vulkan") set(vulkan "metal") # unrelated variable that happens to be named vulkan if(${BACKEND} STREQUAL "metal") # if() receives: vulkan STREQUAL metal ``` `if()` sees the word `vulkan`, finds a variable of that name, and compares its value `metal` with `"metal"`. CMake 4.4.4 evaluated this condition as **true**. The bug depends on which other variables happen to exist, so it can appear when an unrelated module adds one. ## Failure two: an empty value ```cmake set(EMPTY_VAR "") if(${EMPTY_VAR} STREQUAL "") ``` An unquoted empty expansion produces **no argument at all**, so `if()` receives only `STREQUAL ""`. CMake 4.4.4 stopped the configure with: ```plaintext CMake Error at CMakeLists.txt:18 (if): if given arguments: "STREQUAL" "" Unknown arguments specified ``` A related failure happens with a value containing a semicolon: unquoted expansion splits it into several arguments, so `if()` sees extra operands it never expected. ## The safe spellings | Written | `if()` receives | Result | |---|---|---| | `if(BACKEND STREQUAL "metal")` | the name `BACKEND` | Looks up `BACKEND` once; an undefined variable compares as the literal word | | `if("${BACKEND}" STREQUAL "metal")` | the quoted value | Compares the value as a string, never dereferenced again | | `if(${BACKEND} STREQUAL "metal")` | the bare value | Dereferenced again if it names a variable; vanishes if empty | The quoted form is safe because of policy **CMP0054**, introduced in CMake 3.1: quoted and bracketed arguments are not dereferenced or interpreted as keywords. CMake 4.0 removed the policy's OLD behaviour, so under CMake 4 the rule holds for every project. ## Truthiness: if(VAR) versus if(${VAR}) The same double-expansion rule explains the boolean forms: - `if(<constant>)` is true for `1`, `ON`, `YES`, `TRUE`, `Y` or a non-zero number, and false for `0`, `OFF`, `NO`, `FALSE`, `N`, `IGNORE`, `NOTFOUND`, the empty string, or a value ending in `-NOTFOUND`. - `if(VAR)` is true when `VAR` is defined to a value that is not a false constant. An undefined `VAR` is simply false. - `if(${VAR})` first expands, then treats the result as a constant or as **another variable name**: the documentation's example `set(var1 OFF)`, `set(var2 "var1")`, `if(${var2})` evaluates `var1` and is false, while `if(var2)` is true. - A quoted string is false unless it is one of the true constants: `if("${VAR}")` is true for `ON` and false for an arbitrary word such as `vulkan`. ## Things if() never auto-dereferences - **Macro arguments**: inside a `macro()`, `ARGN`, `ARGV0` and the named parameters are text replacements, not variables, so `if(ARGN)` looks for a real variable called `ARGN`. - **Environment and cache references**: `if(ENV{HOME})` is always false; write `$ENV{HOME}` or `$CACHE{NAME}` explicitly, or use `if(DEFINED ENV{HOME})` to test presence. ## Lists in conditions A CMake list is a string whose elements are separated by `;`. To test membership, `IN_LIST` (CMake 3.3) takes the list's **name** on the right and auto-dereferences the left side like any other operand: ```cmake set(BACKENDS vulkan metal d3d12) if("metal" IN_LIST BACKENDS) # true; quoting the left side keeps it a literal ``` Writing `${BACKENDS}` on the right would hand `if()` three separate words and break the expression, the same unquoted-expansion trap in another form. ## A review checklist 1. In comparisons, write variable names bare or quote the expansion; never leave `${...}` unquoted. 2. Test presence with `if(DEFINED NAME)`, not with `if(${NAME})`. 3. Test emptiness with `if(NAME STREQUAL "")` or `if("${NAME}" STREQUAL "")`. 4. Treat a configure error saying `Unknown arguments specified` on an `if` line as an empty unquoted expansion until proven otherwise.

  • Why does if(ENV{CI}) never become true, even on a CI machine?
    `if()` auto-dereferences only normal variables. `ENV{CI}` written bare is just a word that names no normal variable, so the condition is false. Write the reference explicitly, `if("$ENV{CI}")`, to test its truth, or `if(DEFINED ENV{CI})` to test whether it is set at all.
  • How do you test whether a variable is empty without tripping over an empty expansion?
    Write the name bare, `if(NAME STREQUAL "")`, so `if()` dereferences it once, or quote the expansion, `if("${NAME}" STREQUAL "")`, so an empty value still forms an argument. Both keep a left operand in place. To distinguish 'unset' from 'empty', add `if(DEFINED NAME)`.

  • Writes if(${VAR} STREQUAL x) believing ${} is needed to read the value
  • Thinks a quoted if() argument is still looked up as a variable in CMake 4
  • Expects if(ENV{CI}) to test an environment variable
  • Believes if(VAR) errors when VAR is undefined
  • Treats if("${VAR}") as true for any non-empty string

Assumes CMake 4.x: CMP0054 (quoted if() arguments are not dereferenced) dates from 3.1, and CMake 4.0 removed its OLD behaviour.