6

I made a C++ project on Linux, and I grouped source files in many directories to organize myself.

I was using CMake to compile, with one CMakeFiles.txt on each subdirectory.

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

Recently, I opened it with Visual Studio 2015, which found every source file, but just put the entire list on the "Source Files" folder of solution explorer.

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

I plan to have a huge number of files, and it shall be soon difficult to find one.

Is there any way to explicitly tell it to respect the folder hierarchy on solution explorer?

Aracthor
  • 5,757
  • 6
  • 31
  • 59
  • What version of CMake? – James Adkison Sep 15 '15 at 02:23
  • @JamesAdkison I'm using the last one, the 3.3.1. – Aracthor Sep 15 '15 at 05:00
  • 1
    I have added a `assign_source_group` example implementation you might find useful to my answer in [How to set Visual Studio Filters for nested sub directory using cmake](http://stackoverflow.com/questions/31422680/how-to-set-visual-studio-filters-for-nested-sub-directory-using-cmake/31423421#31423421). – Florian Sep 15 '15 at 06:54
  • @JamesAdkison Thanks to this, I made it. Problem solved. – Aracthor Sep 15 '15 at 09:45

2 Answers2

4

Use the source_group command.

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
  • 9,412
  • 2
  • 29
  • 43
3

@James Adkison is correct; source_group is what you want to use. As of CMake 3.8, the improved source_group command now offers a TREE argument to recursively search your source hierarchy to create source groups to match it. Here is a basic solution for the example you provided:

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})
Kevin
  • 16,549
  • 8
  • 60
  • 74