Search code examples
cmake

CMake: Print out all accessible variables in a script


I'm wondering if there is a way to print out all accessible variables in CMake. I'm not interested in the CMake variables - as in the --help-variables option. I'm talking about my variables that I defined, or the variables defined by included scripts.

I'm currently including:

INCLUDE (${CMAKE_ROOT}/Modules/CMakeBackwardCompatibilityCXX.cmake)

And I was hoping that I could just print out all the variables that are here, instead of having to go through all the files and read what was available - I may find some variables I didn't know about that may be useful. It would be good to aid learning & discovery. It is strictly for debugging/development.

This is similar to the question in Print all local variables accessible to the current scope in Lua, but for CMake!

Has anyone done this?


Solution

  • Using the get_cmake_property function, the following loop will print out all CMake variables defined and their values:

    get_cmake_property(_variableNames VARIABLES)
    list (SORT _variableNames)
    foreach (_variableName ${_variableNames})
        message(STATUS "${_variableName}=${${_variableName}}")
    endforeach()
    

    This can also be embedded in a convenience function which can optionally use a regular expression to print only a subset of variables with matching names

    function(dump_cmake_variables)
        get_cmake_property(_variableNames VARIABLES)
        list (SORT _variableNames)
        foreach (_variableName ${_variableNames})
            if (ARGV0)
                unset(MATCHED)
                string(REGEX MATCH ${ARGV0} MATCHED ${_variableName})
                if (NOT MATCHED)
                    continue()
                endif()
            endif()
            message(STATUS "${_variableName}=${${_variableName}}")
        endforeach()
    endfunction()
    

    Or, in a more compact form:

    function(dump_cmake_variables)
        get_cmake_property(_variableNames VARIABLES)
        list (SORT _variableNames)
        foreach (_variableName ${_variableNames})
            if ((NOT DEFINED ARGV0) OR _variableName MATCHES ${ARGV0})
                message(STATUS "${_variableName}=${${_variableName}}")
            endif()
        endforeach()
    endfunction()
    

    To print environment variables, use CMake's command mode:

    execute_process(COMMAND "${CMAKE_COMMAND}" "-E" "environment")