It's best to hide all the details of setting up the variable SRCS
in a CMake macro. The macro can then be called in all the project CMake list files to add sources.
In the CMakeLists.txt
in the project root folder, add the following macro definition:
macro (add_sources)
file (RELATIVE_PATH _relPath "${PROJECT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}")
foreach (_src ${ARGN})
if (_relPath)
list (APPEND SRCS "${_relPath}/${_src}")
else()
list (APPEND SRCS "${_src}")
endif()
endforeach()
if (_relPath)
# propagate SRCS to parent directory
set (SRCS ${SRCS} PARENT_SCOPE)
endif()
endmacro()
add_sources(main.cpp)
add_subdirectory(dir1)
add_subdirectory(dir2)
message(STATUS "${SRCS}")
The macro first computes the path of the source file relative to the project root for each argument. If the macro is invoked from inside a project sub directory the new value of the variable SRCS needs to be propagated to the parent folder by using the PARENT_SCOPE option.
In the sub directories, you can simply add a macro call, e.g. in dir1/CMakeLists.txt
add:
add_sources(file1.cpp file2.cpp)
And in dir2/CMakeLists.txt
add:
add_sources(file3.cpp file4.cpp)