I wonder why often variables in CMake are wrapped with a dollar sign and curly brackets. For example, I saw this call in a CMake tutorial.
include_directories(${PROJECT_BINARY_DIR})
But from what I tried, this does the same thing.
include_directories(PROJECT_BINARY_DIR)
When is the wrapping with ${...}
needed and what does it mean? Why are variables often wrapped with this even if it makes no difference?
Quoting the CMake documentation:
In other words, writing
PROJECT_BINARY_DIR
refers, literally, to the string "PROJECT_BINARY_DIR". Encapsulating it in${...}
gives you the contents of the variable with the name PROJECT_BINARY_DIR.Consider:
As you have probably guessed already,
include_directories(PROJECT_BINARY_DIR)
simply attempts to add a subdirectory of the name PROJECT_BINARY_DIR to the include directories. On most build systems, if no such directory exists, it will simply ignore the command, which might have tricked you into the impression that it works as expected.A popular source of confusion comes from the fact that
if()
does not require explicit dereferencing of variables:Again the documentation explains this behavior:
In particular, one can come up with weird examples like:
Which will take the
TRUE
branch in the variable case, and theFALSE
branch in the constant case. This is due to the fact that in the constant case, CMake will go look for a variableBLA
to perform the check on (which is not defined, hence we end up in the FALSE branch).