cmake_minimum_required(VERSION 3.10) project(toplevel LANGUAGES C) add_subdirectory(libraries) set(ALL_MY_PROJECT_TARGETS "" CACHE INTERNAL "Global list") # Function to recursively collect all targets function(get_all_project_targets _target_list_var _current_dir) # Get targets defined directly in the current directory get_property(_targets_in_dir DIRECTORY "${_current_dir}" PROPERTY BUILDSYSTEM_TARGETS) message("_targets_in_dir: ${_targets_in_dir}") list(APPEND _ALL_MY_PROJECT_TARGETS ${ALL_MY_PROJECT_TARGETS} ${_targets_in_dir}) set(ALL_MY_PROJECT_TARGETS ${_ALL_MY_PROJECT_TARGETS} "" CACHE INTERNAL "") message("ALL_MY_PROJECT_TARGETS: ${ALL_MY_PROJECT_TARGETS}") message("current_dir: ${_current_dir}") get_filename_component(CURRENT_DIR_NAME "${_current_dir}" NAME) message(" - NAME: ${CURRENT_DIR_NAME}") # Get subdirectories of the current directory get_property(_subdirs DIRECTORY "${_current_dir}" PROPERTY SUBDIRECTORIES) foreach(_subdir IN LISTS _subdirs) # Recursively call for each subdirectory message("_subdir: ${_subdir}") get_all_project_targets(${_target_list_var} "${_subdir}") endforeach() endfunction() # Call the function from the top-level CMakeLists.txt get_all_project_targets(ALL_MY_PROJECT_TARGETS "${CMAKE_CURRENT_SOURCE_DIR}") # Print the list of all targets message("All CMake Targets in this project:") foreach(target_name IN LISTS ALL_MY_PROJECT_TARGETS) message("- ${target_name}") endforeach() # Do stuff add_executable(${PROJECT_NAME}-exe main.c) target_link_libraries(${PROJECT_NAME}-exe library_a-lib library_b-lib)