GroupSourcesByFolder.cmake
GroupSourcesByFolder.cmake copied to clipboard
Automatically group sources by folder structure for Visual Studio/Xcode generators
GroupSourcesByFolder.cmake
About
When using CMake to generate Visual Studio/Xcode targets, source organization can become very convoluted as by default CMake creates two single source groups for all headers and for source files, completely ignoring any organization in the local file structure. GroupSourcesByFolder.cmake automatically re-groups the source files into a structure resembling the original file structure. The script is based on this blog post by Matthieu Brucher.
Example
| Before | After |
|---|---|
![]() |
![]() |
Usage
Integrate GroupSourcesByFolder.cmake into your project and call GroupSourcesByFolder with your target as an argument.
add_library(MyLibrary ${sources})
GroupSourcesByFolder(MyLibrary)
How to integrate
Using CPM.cmake (recommended)
Run the following from the project's root directory to add CPM to your project.
mkdir -p cmake
wget -O cmake/CPM.cmake https://raw.githubusercontent.com/TheLartians/CPM.cmake/master/cmake/CPM.cmake
Add the following lines to the project's CMakeLists.txt after calling project(...).
include(cmake/CPM.cmake)
CPMAddPackage(
NAME GroupSourcesByFolder.cmake
GITHUB_REPOSITORY TheLartians/GroupSourcesByFolder.cmake
VERSION 1.0
)
Using git submodules (not suited for libraries)
Run the following from the project's root directory.
git submodule add https://github.com/TheLartians/GroupSourcesByFolder.cmake
In add the following lines to the project's CMakeLists.txt after calling project(...).
add_subdirectory(GroupSourcesByFolder.cmake)
See also
- Format.cmake - clang-format targets for CMake
- Ccache.cmake - a Ccache integration for CMake with Xcode support

