The set()
command in CMake is used to assign a value to a variable. It provides a way to define and manage variables within CMake scripts, allowing us to control project behavior and specify paths. This Answer introduces this command with a practical example.
The syntax of the set()
command is as follows:
set(<variable_name> <value> [CACHE <type> <docstring> [FORCE]])
Its parameters can be explained as follows:
<variable_name>
: This is the name of the variable to be set.
<value>
: This is the value to assign to the variable.
[CACHE <type> <docstring> [FORCE]]
: These are optional arguments for caching the variable, specifying the type of data it holds, providing documentation, and forcing the variable to be set again if it was previously set.
In the code example below, we set paths inside two library directories:
cmake_minimum_required(VERSION 3.0) project(SetCommandExample) set(BUILD_TESTS OFF CACHE BOOL "Build tests") if(BUILD_TESTS) add_subdirectory(tests) endif() set(INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include) set(LIBRARY_DIRS ${PROJECT_SOURCE_DIR}/lib) message("Include directories: ${INCLUDE_DIRS}") message("Library directories: ${LIBRARY_DIRS}")
Line 4: The set()
command is used to set the BUILD_TESTS
variable to OFF
. This variable controls whether tests should be built. The CACHE BOOL
option caches the variable’s value, configuring it by users or across different CMake runs. The "Build tests"
string explains the purpose of the variable.
Lines 6–8: The conditional statement (if(BUILD_TESTS)
) checks the value of the BUILD_TESTS
variable. If it’s enabled (ON
), the script includes the tests
directory using the add_subdirectory()
command. This demonstrates how the variables set with set()
can influence code behavior.
Lines 10–11: The set()
command sets two variables (INCLUDE_DIRS
and LIBRARY_DIRS
) to specify the “include” and “library” directories, respectively. These paths are based on the ${PROJECT_SOURCE_DIR}
variable representing the project’s root directory. Here, set()
is used to define paths that are then used elsewhere in the script or subsequent CMake configurations.
Lines 13–14: The message()
command is used to print out the values of the INCLUDE_DIRS
and LIBRARY_DIRS
variables. This illustrates how set()
can be used in conjunction with other CMake commands to provide feedback or debug information during the project configuration process.
The set()
command in CMake is fundamental for manipulating variables within CMake scripts. It helps us configure projects, build options, and specify paths efficiently. Understanding how to use set()
leads to more flexibility and helps us manage our CMake projects efficiently.