Variable Scope and Lists

Let's learn about variable scope and more complex data structures, such as lists, in CMake.

We'll cover the following

Variable scope

Variable scope is probably the hardest part of the whole concept of the CMake Language. This is maybe because we're accustomed to how things are done in more advanced languages that support namespaces and scope operators. CMake doesn't have those mechanisms, so it deals with this issue in its own, somewhat unusual way.

Just to clarify, variable scopes as a general concept are meant to separate different layers of abstraction so that when a user-defined function is called, variables set in that function are local to it. These local variables aren't affecting the global scope, even if the names of the local variables are exactly the same as the global ones. If explicitly needed, functions should have read/write access to global variables as well. This separation of variables (or scopes) has to work on many levels—when one function calls another, the same separation rules apply.

CMake has two scopes:

  • Function scope: For when custom functions defined with function() are executed.

  • Directory scope: For when a CMakeLists.txt listfile in a nested directory is executed from the add_subdirectory() command.

When a nested scope is created, CMake simply fills it with copies of all the variables from the current scope. Subsequent commands will affect these copies. But as soon as the execution of the nested scope is completed, all copies are deleted, and the original parent scope is restored.

Let's consider the following scenario:

Get hands-on with 1200+ tech skills courses.