Get list of CMake target names

CMake build targets are declared by “add_[executable,library,custom_target]” commands. Targets can be dynamically set by arbitrarily complex foreach(), if(), etc. logic. A list of CMake targets in the directory scope is retrieved by the BUILDSYSTEM_TARGETS directory property.

The variable “target_names” contains all the target names previously added in the CMakeLists.txt in the DIRECTORY scope. Retrieving the list of targets in a whole project, or in a FetchContent dependency is possible with this CMake function:

function(print_targets dir)
    get_property(subdirs DIRECTORY "${dir}" PROPERTY SUBDIRECTORIES)
    foreach(sub IN LISTS subdirs)
        print_targets("${sub}")
    endforeach()

    get_directory_property(targets DIRECTORY "${dir}" BUILDSYSTEM_TARGETS)
    if(targets)
        message("Targets in ${dir}:")
        foreach(t IN LISTS targets)
            message("  • ${t}")
        endforeach()
    endif()
endfunction()

Use this function like:

print_targets("${CMAKE_CURRENT_SOURCE_DIR}")

Or supposing FetchContent, here using “googletest”:

FetchContent_MakeAvailable(googletest)

FetchContent_GetProperties(googletest)
print_targets(${googletest_SOURCE_DIR})

results in:

Targets in _deps/googletest-src/googletest:
  • gtest
  • gtest_main
Targets in _deps/googletest-src/googlemock:
  • gmock
  • gmock_main

Note: get_property(test_names GLOBAL PROPERTY BUILDSYSTEM_TARGETS) will return an empty list–DIRECTORY scope must be used.