Working With Variables

Let's learn about all kinds of variables in CMake.

Variables in CMake are a surprisingly complex subject. Not only are there three categories of variables—normal, cache, and environment—but they also reside in different scopes, with specific rules on how one scope affects the other. Very often, a poor understanding of all these rules becomes a source of bugs and headaches. We recommend you study this section with care and make sure you understand all of the concepts before moving on.

Let's start with some key facts about variables in CMake:

  • Variable names are case-sensitive and can include almost any character.

  • All variables are stored internally as strings, even if some commands can interpret them as values of other data types (even lists!).

  • The basic variable manipulation commands are set() and unset(), but there are other commands that can affect variables, such as string() and list().

To set a variable, we simply call set(), providing its name and the value. Click on the “Run” button and execute cmake -P set.cmake command in the terminal.

Get hands-on with 1400+ tech skills courses.