When to use ${} around variable names


Recently I put up a change in our product’s CMakeLists.txt to eliminate unnecessary use of ${} in tests around variables CMAKE_SYSTEM_NAME and CMAKE_CXX_COMPILER_ID. That prompted a colleague to ask “when is it necessary to use ${} around variable names?” and I had to admit my ignorance :wink:

Is there a rule or guidelines for when the ${} is necessary?


Rob Boehne

The only place they aren’t necessary (and it’s not being passed as an output variable to a command) is in the if and while commands and the foreach (IN LISTS) right-hand side. Basically, if you have a binary predicate, you can take either argument in the form of "${var}" and just use var. Note that unary predicates like DEFINED, TARGET, IS_ABSOLUTE, etc. do not do automatic dereferencing.

There’s also things like the list() command where it expects the name of a variable to operate on rather than the variable’s contents.

Ah, I put that under the “output variable” classification. It’s just also an input :slight_smile: .