Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use CMake variables

📅 2014-Feb-14 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cmake, variable ⬩ 📚 Archive

CMake uses many variables that are officially documented. These have default values or values that are based on your project environment. You are allowed to change the value of these variables in your CMakeLists.txt. In addition, you can also define any variables you need. In fact, defining your own custom variables makes your CMakeLists.txt file easy to read and maintain.

To list all the variables that are defined and their current values, try this in a directory that has a CMakeLists.txt file:

$ cmake -LAH

A list of common variables used internally by CMake can be seen here. You can change the value of these variables in your CMakeLists.txt to modify the behavior of CMake for your project. See below for how to set variables.

To set a variable to a single value in your CMakeLists.txt file:

set(JoeLibraries -lfoo)

A variable can be set a list of values:

set(JoeLibraries -lfoo -lbar -lstarwars)

It can also be indented in different ways for ease of reading:

set(
    JoeLibraries
    -lfoo
    -lbar
    -lstarwars
    )

To use a variable in another command:

target_link_libraries(
    helloworld
    ${JoeLibraries}
    )

A variable can also be used to in setting the value of another variable:

set(
    BruceLibraries
    -lkungfu
    ${JoeLibraries}
    )

Strings can be appended naturally to variables:

set(CurDir /home/joe/helloworld)
set(BinDir ${CurDir}/bin)

To check if a variable exists:

if(CurDir)
    message("CurDir variable exists")
endif(CurDir)

To check if a variable does not exist:

if(NOT CurDir)
    message("CurDir variable does not exist")
endif(NOT CurDir)

To check if variable value is equal to a string:

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    message("Build is Debug type")
endif(CMAKE_BUILD_TYPE STREQUAL "Debug")

Note that the comparison is case-sensitive.

If you want case-insensitive compare, you will need to convert the variable value to lowercase, store it in a new variable and compare that:

STRING(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE_LOWER)
if(CMAKE_BUILD_TYPE_LOWER STREQUAL "debug")
    message("Build is debug type")
endif()

Tried with: CMake 2.8.7 and Ubuntu 12.04 LTS


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧