function(group_sources root)
function(__group_sources__ root prefix)
file(GLOB entries RELATIVE "${root}" "${root}/*")
foreach(entry ${entries})
set(abspath "${root}/${entry}")
if(IS_DIRECTORY "${abspath}")
__group_sources__("${abspath}" "${prefix}/${entry}")
else()
list(APPEND group "${abspath}")
endif()
endforeach()
string(REPLACE "/" "\\" prefix "${prefix}")
source_group("${prefix}" FILES ${group})
endfunction()
get_filename_component(prefix "${root}" NAME)
__group_sources__("${root}" "${prefix}")
endfunction()
Usage:
group_sources("${CMAKE_SOURCE_DIR}/src")
group_sources("${CMAKE_SOURCE_DIR}/include")
Note this function only creates filters in project, you still need to add source files by ADD_EXECUTABLE or ADD_LIBRARY commands. For more complete example, see this gist.