Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding files to source_group in CMake

Tags:

cmake

I am having an issue with CMake in which I cannot get my files to be added to folders/filters inside of Visual Studio.

# Add folders to filters
file(GLOB_RECURSE DATABASE_SRCS     RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/database *.cpp *.h)
file(GLOB_RECURSE LOG_SRCS          RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/log *.cpp *.h)
file(GLOB_RECURSE NETWORK_SRCS      RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/network *.cpp *.h)
file(GLOB_RECURSE THREADING_SRCS    RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/threading *.cpp *.h)
file(GLOB_RECURSE UTILS_SRCS        RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/utils *.cpp *.h)

source_group(database   FILES ${DATABASE_SRCS})
source_group(log        FILES ${LOG_SRCS})
source_group(network    FILES ${NETWORK_SRCS})
source_group(threading  FILES ${THREADING_SRCS})
source_group(utils      FILES ${UTILS_SRCS})

An issue that might be causing this problem is that the GLOB_RECURSE's return the files that are in ${CMAKE_CURRENT_SOURCE_DIR} but relative to the /database (or whatever other directory).

For example, there is a file in database/ called dbcore.cpp. This file gets added to DATABASE_SRCS as dbcore.cpp, but files in the main directory (i.e. ${CMAKE_CURRENT_SOURCE_DIR}) also get added, but have a path relative to database/, such as ../common.h.

Another issue may be that inside of the Visual Studio project the default "Header Files" and "Source Files" filters already exist.

I am using CMake 2.8.6 and Visual Studio 11/2012.

like image 467
Nick Taylor Avatar asked Jun 10 '12 20:06

Nick Taylor


1 Answers

To avoid the file(GLOB_RECURSE... calls returning all files every time, use something like:

file(GLOB_RECURSE DATABASE_SRCS
         RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
         ${CMAKE_CURRENT_SOURCE_DIR}/database/*.cpp
         ${CMAKE_CURRENT_SOURCE_DIR}/database/*.h)

This will set the value of DATABASE_SRCS to database/dbcore.cpp;database/dbcore.h;... which should make your source_group calls work properly.

However, from the documentation for file(GLOB:

We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.

To see the full details, run

cmake --help-command file

The commonly-recommended way to list project files is to add them by hand to the CMakeLists.txt.

To answer your final issue, if Visual Studio's default "Header Files" and "Source Files" are empty (i.e. all files appear in other folders), they don't appear. The presence of these defaults doesn't affect any folders created using source_group.

like image 54
Fraser Avatar answered Oct 06 '22 00:10

Fraser