Как я могу аккуратно поместить файлы в фильтр «root» в Visual Studio с помощью CMake?

#c #visual-studio #cmake

Вопрос:

Мы используем CMake для создания наших решений Visual Studio. Наш проект представляет собой «целое» приложение, состоящее из заголовочных файлов вместе с исходными файлами (.h/.cpp).

Нам нравится, чтобы исходные/заголовочные файлы были хорошо вложены под фильтрами в Visual Studio («папки» в обозревателе решений), так же, как мы видим их в проводнике файлов Windows.

Поэтому мы придумали что-то подобное, чтобы достичь этого:

 # ...the files are added to the project in another way.

#
# Group files under filters
#
file(GLOB source_files *.cpp *.h )
file(GLOB source_files_benchmark                benchmark/*.cpp benchmark/*.h )
file(GLOB source_files_builder                  builder/*.cpp builder/*.h )
file(GLOB source_files_demo                     demo/*.cpp demo/*.h )
file(GLOB source_files_dashboard                dashboard/*.cpp dashboard/*.h )
file(GLOB source_files_gsl                      gsl/* )
file(GLOB source_files_jsonUtil2                jsonUtil2/*.cpp jsonUtil2/*.h )

source_group( ""                            FILES ${source_files} )
source_group( "benchmark"                   FILES ${source_files_benchmark} )
source_group( "builder"                     FILES ${source_files_builder} )
source_group( "dashboard"                   FILES ${source_files_dashboard} )
source_group( "demo"                        FILES ${source_files_demo} )
source_group( "gsl"                         FILES ${source_files_gsl} )
source_group( "jsonUtil2"                   FILES ${source_files_jsonUtil2} )
 

(Пожалуйста, обратите внимание, что мы используем глобус файла «зло» для создания наших списков. Мы осознаем риски и выяснили, что они доставляли меньше неудобств, чем добавление новых файлов вручную; Я также не думаю, что способ получения списка файлов здесь уместен.)

Это работает, и у нас есть хорошая структура проекта, когда мы загружаем проект в Visual Studio.

Я подумал, что, вероятно, мог бы улучшить это, и предложил это альтернативное решение:

 # Nicely put the files into "filters" in Visual Studio. We used to do this 
# manually but this way requires less work, overall. 

# Get all the files CMake knows about.
get_target_property(local_app_sources ${my_target} SOURCES)
get_target_property(local_app_headers ${my_target} HEADERS)

set(local_app_files ${local_app_sources})
list(APPEND local_app_files ${local_app_headers})

# Create two lists, one we'll use for the "root", and one we'll use for the "in 
# folders". More details below.
set(local_root_files ${local_app_files})
set(local_in_folder_files ${local_app_files})

list(FILTER local_root_files      EXCLUDE REGEX ".*/.*")
list(FILTER local_in_folder_files INCLUDE REGEX ".*/.*")

# For some reasons, CMake will place the files that are at the "root" under the 
# "Source Files" filter in Visual Studio, so we have moved those files to their 
# own list. We use the source_group(TREE command to make a nice tree with the 
# files that are under a folder, and we'll use the default version of the 
# command to place the files that are at the root into an "empty string" folder 
# (no folder), so that they'll be placed at the root. 
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${local_in_folder_files})
source_group( "" FILES ${local_root_files} )
 

I’m happy that we don’t have to add new folders manually anymore. However, I find it’s still a bit verbose and I’m wondering if I could achieve the same with a single call to source_group(TREE , without the need to split the list and put the files that are at the «root» explicit into that folder.

How can I achieve this? What am I missing?

Я попробовал параметр «ПРЕФИКС», но он просто поместил все в эту папку (в итоге я <prefix>/Source Files/src.. получил), и нам также не нужен префикс.

Мы используем CMake 3.8.что-то (я знаю, это старое, и мы должны обновить… когда-нибудь мы до этого доберемся.)