您可以构建构建,以便最终结果确实是一个包含所有内容的巨大目标,但是进入该构建的子组件以分段方式指定,这将使设置更接近其源。
作为一个基本示例,我设置了一个测试项目
基础 CMakeLists.txt:
cmake_minimum_required(VERSION 3.14)
project(cmake_test)
add_library(megalib SHARED dummy.cpp)
add_subdirectory(a)
add_subdirectory(b)
一个/CMakeLists.txt:
target_include_directories(megalib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_sources(megalib PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/a.cpp)
b/CMakeLists.txt:
target_include_directories(megalib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_sources(megalib PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/b.cpp)
以及生成的编译日志(使用 Ninja 生成器):
[1/4] /usr/bin/c++ -Dmegalib_EXPORTS -I/tmp/cmake-test/a -I/tmp/cmake-test/b -fPIC -MD -MT CMakeFiles/megalib.dir/dummy.cpp.o -MF CMakeFiles/megalib.dir/dummy.cpp.o.d -o CMakeFiles/megalib.dir/dummy.cpp.o -c /tmp/cmake-test/dummy.cpp
[2/4] /usr/bin/c++ -Dmegalib_EXPORTS -I/tmp/cmake-test/a -I/tmp/cmake-test/b -fPIC -MD -MT CMakeFiles/megalib.dir/a/a.cpp.o -MF CMakeFiles/megalib.dir/a/a.cpp.o.d -o CMakeFiles/megalib.dir/a/a.cpp.o -c /tmp/cmake-test/a/a.cpp
[3/4] /usr/bin/c++ -Dmegalib_EXPORTS -I/tmp/cmake-test/a -I/tmp/cmake-test/b -fPIC -MD -MT CMakeFiles/megalib.dir/b/b.cpp.o -MF CMakeFiles/megalib.dir/b/b.cpp.o.d -o CMakeFiles/megalib.dir/b/b.cpp.o -c /tmp/cmake-test/b/b.cpp
[4/4] : && /usr/bin/c++ -fPIC -shared -Wl,-soname,libmegalib.so -o libmegalib.so CMakeFiles/megalib.dir/dummy.cpp.o CMakeFiles/megalib.dir/a/a.cpp.o CMakeFiles/megalib.dir/b/b.cpp.o && :
然后设置一些宏以减少子目录之间的重复量可能很有用。(特别是为了减少必须为添加到子目录中的每个源文件指定绝对文件路径的负担。)