如何在解决方案资源管理器中保留源文件夹层次结构?

How to keep source folders hierarchy on solution explorer?

我在Linux上做了一个C++项目,我把源文件分到很多目录里自己整理。

我是用CMake编译的,每个子目录一个CMakeFiles.txt

srcs
|--folderA
|  |--Toto.cpp
|  |--Tata.cpp
|
|--folderB
|  |--Foo.cpp
|  |--Bar.cpp
[...]

最近,我用Visual Studio 2015打开它,它找到了每个源文件,但只是将整个列表放在解决方案资源管理器的"Source Files"文件夹中。

Source Files
|--Toto.cpp
|--Tata.cpp
|--Foo.cpp
|--Bar.cpp

我打算有大量的文件,很快就会很难找到一个。

有没有办法明确告诉它遵守解决方案资源管理器上的文件夹层次结构?

使用source_group命令。

source_group(<name> [FILES <src>...] [REGULAR_EXPRESSION <regex>])

Defines a group into which sources will be placed in project files. This is intended to set up file tabs in Visual Studio. The options are:

FILES Any source file specified explicitly will be placed in group . Relative paths are interpreted with respect to the current source directory.

REGULAR_EXPRESSION Any source file whose name matches the regular expression will be placed in group .

@James Adkison 是正确的; source_group 是您要使用的。从 CMake 3.8 开始,改进的 source_group 命令现在提供了一个 TREE 参数来递归搜索您的源层次结构以创建源组来匹配它。这是您提供的示例的基本解决方案:

project(MyProj)

set(MyProj_SOURCES
    "folderA/Toto.cpp"
    "folderA/Tata.cpp"
    "folderB/Foo.cpp"
    "folderB/Bar.cpp"
)

add_executable(Main ${MyProj_SOURCES})

# Create the source groups for source tree with root at CMAKE_CURRENT_SOURCE_DIR.
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${MyProj_SOURCES})