在使用cmake工具构建项目时,需要向target中添加源文件,比如:add_executable (DesignPattern main.cpp)
。这样会产生一个问题,当文件少的时候可以维护,但是,当文件有成百上千时,想要维护就会变得很麻烦。虽然出问题时解决起来应该不算复杂,但如果有自动扫描的方式还是会好很多。下面是一个可以实现自动扫描的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| set(GLOBAL_LIST "" CACHE INTERNAL "Global list")
function(append_to_global_list value) set(GLOBAL_LIST "${GLOBAL_LIST}" ${value} CACHE INTERNAL "Global list" FORCE) endfunction()
function(findSrc dirPath) set(VAC_INCLUDE_DIR ${dirPath})
file(GLOB ALL_ITEMS ${VAC_INCLUDE_DIR}/*) foreach (ITEM ${ALL_ITEMS}) STRING(FIND ${ITEM} ".cpp" pos1) STRING(FIND ${ITEM} ".h" pos2) if (pos1 GREATER -1 OR pos2 GREATER -1) append_to_global_list(${ITEM}) endif () if (IS_DIRECTORY ${ITEM}) findSrc(${ITEM}) endif () endforeach () endfunction()
findSrc(${CMAKE_SOURCE_DIR}/Src)
set(GLOBAL_LIST "${GLOBAL_LIST}" CACHE INTERNAL "Global list" FORCE)
add_executable (target ${GLOBAL_LIST})
|
注意,当增加或者删除文件时,需要重新运行cmake文件。
完整文件链接:https://gitee.com/liangxi1125/designpatterns/blob/master/CMakeLists.txt