CMakeList DLC速通手脚架

受够了重复add_executable带来的键盘磨损?受够了add_subdirectory眼花缭乱?

此文摘录一些好用的Cmake函数,以用于项目构建。

获取当前文件夹名

1
2
3
4
macro(GET_DIR_NAME DIRNAME)
string(REGEX MATCH "([^/]*)$" TMP ${CMAKE_CURRENT_SOURCE_DIR})
set(${DIRNAME} ${TMP})
endmacro(GET_DIR_NAME DIRNAME)

使用方法:

1
2
GET_DIR_NAME(DIRNAME)
message(${DIRNAME})

添加所有子文件夹至工程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
macro(ADD_ALL_SUBDIR)
file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
set(dirlist "")
foreach(child ${children})
if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${child})
if(${child} STREQUAL "CMakeFiles")
else(${child})
LIST(APPEND dirlist ${child})
endif()
endif()
endforeach()
foreach(subdir ${dirlist})
add_subdirectory(${subdir})
endforeach()
endmacro(ADD_ALL_SUBDIR)

顾名思义,不用再重复add_subdirectory了。

快速创建工程

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
macro(SETUP_PROJECT MODE TARGET_NAME STR_TARGET_SOURCES STR_TARGET_LIBS)
string(REPLACE " " ";" LIST_TARGET_SOURCES ${STR_TARGET_SOURCES})
string(REPLACE " " ";" LIST_TARGET_LIBS ${STR_TARGET_LIBS})
if(${STR_TARGET_SOURCES} STREQUAL " ")
message(WARNING "Target [${TARGET_NAME}] has no source, so it won't be generated.")
else()
if(${MODE} STREQUAL "EXE")
add_executable( ${TARGET_NAME} ${LIST_TARGET_SOURCES})
set(INSTALL_DIR "bin")
install (TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_DIR})
elseif(${MODE} STREQUAL "LIB")
add_library(${TARGET_NAME} ${LIST_TARGET_SOURCES})
#set(INSTALL_DIR "lib/Gen")
else()
message(FATAL_ERROR "Mode [${MODE}] is not supported, so target [TARGET_NAME] is not generated!")
set(MODE_NOTSUPPORT " ")
endif()
if(NOT DEFINED MODE_NOTSUPPORT)
if( NOT ${FOLDER_NAME} STREQUAL " ")
SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES FOLDER ${FOLDER_NAME})
endif()
if(NOT ${STR_TARGET_LIBS} STREQUAL " ")
target_link_libraries( ${TARGET_NAME} ${LIST_TARGET_LIBS} )
endif()
#install (TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_DIR})
message(STATUS "Setup Target ${FOLDER_NAME}/[${TARGET_NAME}] success")
endif()
endif()
endmacro(SETUP_PROJECT TARGET_NAME STR_TARGET_SOURCES STR_TARGET_LIBS)

使用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
### 在子文件夹中创建CMakeLists.txt进行编辑
set(MODE "LIB")
#项目名,默认为目录名
GET_DIR_NAME(DIRNAME)
set(TARGET_NAME ${DIRNAME})
#多个源文件用 [空格] 分隔
#如:set(STR_TARGET_SOURCES "main.cpp src_2.cpp")
set(STR_TARGET_SOURCES "main.cpp ${CMAKE_SOURCE_DIR}/include/lib.h")
#多个库文件用 [空格] 分隔,如果为空,就输入[一个空格]
#如:set(STR_TARGET_LIBS "lib1.lib lib2.lib")
set(STR_TARGET_LIBS " ")

SETUP_PROJECT(${MODE} ${TARGET_NAME} ${STR_TARGET_SOURCES} ${STR_TARGET_LIBS})
Share