CMake Variables

CMake, like any other language, has variables. CMake variables are all treated as strings but they have the usual types.

To set a variable we use the set command and to use a variable we use the ${} notation:

set(VAR_NAME "value")
message("${VAR_NAME}")

CMake variables names are case sensitive and a non-existent variable will always be replaced by an empty string. If we want to remove a variable, there is the unset command:

unset(VAR_NAME)

We can even build variable names from other variables!

set(PLATFORM "LINUX")
set(HELLO_MESSAGE_WINDOWS "Hello Windows builders")
set(HELLO_MESSAGE_LINUX "Hello Linux builders")

message(${HELLO_MESSAGE_${PLATFORM}})

CMake also has cache variables which are variables that survive between runs:

set(MY_CACHE_VAR "In the cache" CACHE STRING "Help text for MY_CACHE_VAR")

We can override a cache variable by passing the -D flag in the cmake command:

cmake -D MY_CACHE_VAR="Overridden" ..

We can do the usual finding and replacing in strings:

string(FIND "This is the from string" "string", FIND_RESULT)

We don’t have to declare the variable FIND_RESULT before using the string command.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.