Print out all CMake variables

cpp

Sometimes, when working with CMake, it can be helpful to see all the defined variables and their values. Here is a simple way to print them all out.

Implementation

First, define a CMake function that prints out all variables and their values.

1
2
3
4
5
6
7
8
function(print_all_variables)
  message(STATUS "CMake Variables:")
  get_cmake_property(_variableNames VARIABLES)
  list(SORT _variableNames)
  foreach (_variableName ${_variableNames})
    message(STATUS "${_variableName}=${${_variableName}}")
  endforeach()
endfunction()

Then call it.

print_all_variables()

That’s it. This shows you the user defined variables and their values.

This is a pretty well known trick, more variations can be found on the internet, for example on this old stackoverflow discussion.

Example output

...
-- Z_VCPKG_MANIFEST_INSTALL_RESULT=0
-- Z_VCPKG_ROOT_DIR=/Users/a4z/vcpkg
-- Z_VCPKG_TARGET_TRIPLET_ARCH=arm64
-- Z_VCPKG_TARGET_TRIPLET_PLAT=osx
-- Z_VCPKG_TOOLCHAIN_DIR=/Users/a4z/vcpkg/scripts/buildsystems
-- Z_VCPKG_UNUSED=VCPKG_INSTALL_OPTIONS
....

Showing also cache variables

If you want to see all the cache variables, just replace the VARIABLES with CACHE_VARIABLES in line 3

get_cmake_property(_variableNames CACHE_VARIABLES)

Now you see also variables like this

...
-- CMAKE_COMMAND=/opt/homebrew/bin/cmake
-- CMAKE_COMPILE_WARNING_AS_ERROR=OFF
-- CMAKE_CONFIGURATION_TYPES=Debug;Release;RelWithDebInfo
-- CMAKE_CPACK_COMMAND=/opt/homebrew/bin/cpack
-- CMAKE_CTEST_COMMAND=/opt/homebrew/bin/ctest
-- CMAKE_EXTRA_GENERATOR=
...

Variable variables

The only notable thing in this snippet is this line:

message(STATUS "${_variableName}=${${_variableName}}")

This shows how you can pack variable names into a variable and dereference them to get the name and the value.

There are only very few cases where this is ever needed. A debug print function, like the above, is one of them.

Another use case

Another use case would be writing a CMake function that takes a variable, and depending on whether you are on Windows or Linux or Mac, prefix every value of that variable with a platform-dependent string.

This can be a motivating example to write a function that does this for you, dear reader. If you have another one, please let me know!