How to set the FOLDER property for all Targets in a given subdirectory

We have an uber-project that brings in several sub-projects via add_subdirectory().
Several of these creates a large number of static library Targets which they then assemble into the dynamic libraries and executables that we actually consume in the uber-project.

This results in the UI of the Visual Studio IDE “Solution” pane showing all the targets in a flat list, including all the ‘private’ static libraries for each of the subprojects.
As there are a really large number of Targets in some of the sub-directories, this makes it quite difficult to quickly find the proper sub-project.

I’d like to organise them into folders, however the only option I’ve found so far is set_target_properties(list of targets PROPERTIES FOLDERS “folder”)

While that works, it’s not really maintainable because I have to list all the Targets created by the sub-project, most of which are static libraries whose names are effectively “hidden” from the uber-project.

Is there a way to set the FOLDER property for all the targets created via add_directory(), so I can place the whole thing into an appropriate folder without needing to know the names of any of the private targets?

A suitable approach is described in this reply, you can instead set the FOLDER property instead.

I used this function I found in a gist: Find all CMake targets declared in a directory (recursively) · GitHub

function(print_all_targets DIR)
    get_property(TGTS DIRECTORY "${DIR}" PROPERTY BUILDSYSTEM_TARGETS)
    foreach(TGT IN LISTS TGTS)
        message(STATUS "Target: ${TGT}")
        # TODO: Do something about it
    endforeach()

    get_property(SUBDIRS DIRECTORY "${DIR}" PROPERTY SUBDIRECTORIES)
    foreach(SUBDIR IN LISTS SUBDIRS)
        print_all_targets("${SUBDIR}")
    endforeach()
endfunction()

print_all_targets(myFolder)
1 Like

The target property FOLDER is pre-initialised from the variable CMAKE_FOLDER if that is set when the target is created (see its docs). So, in order to store all targets from a subdirectory in a particular folder, all you have to do is this:

set(CMAKE_FOLDER FolderFor/Subdir)
add_subdirectory(sub/dir)
unset(CMAKE_FOLDER)