1.定义工程文件:
set(ProjectName, "myproj")
project(${ProjectName})
2.添加子工程:
set(SubProj, "mysubproj")
add_subdirectory(${SubProj})
3.添加包含目录:
include_directories(../3rd/include)
4.添加源码目录:
aux_source_directory(. SRC_LIST) // 包含当前目录里源码(c,cpp,cxx)
5.添加预定义:
add_definitions(-DDEBUG)
6.添加依赖库目录:
link_directories("${CMAKE_CURRENT_SOURCE_DIR}/../3rd/lib") // 注意使用绝对路径
7.创建生成目标:
file(GLOB_RECURSE INC_LIST "*.h")
add_library(${ProjectName} STATIC ${SRC_LIST} ${INC_LIST}) // 生成静态链接库,如需将头文件加入VS工程列表,需加入头文件列表
add_library(${ProjectName} SHARED ${SRC_LIST}) // 生成动态链接库
add_executable(${ProjectName} ${SRC_LIST}) // 生成可执行程序
8.指定依赖库:
set(LINK_LIB lib1 lib2 lib3)
target_link_libraries(${ProjectName} debug | optimized | general "${LINK_LIB}") // debug 针对Debug,optimized针对Release, general针对两者
9.指定输出文件路径:
SET_TARGET_PROPERTIES(${project_name} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ../lib) // 指定动态库输出路径
SET_TARGET_PROPERTIES(${project_name} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ../lib) // 指定静态库输出路径
SET_TARGET_PROPERTIES(${project_name} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ../bin) // 指定可执行程序输出路径
10.过滤文件:
list(FILTER SRC_LIST EXCLUDE REGEX "xx.c")
11.按文件目录添加VS文件夹筛选器
function(group_by_dir src_dir)
foreach(FILE ${ARGN})
# 获取文件绝对路径
get_filename_component(FULL_NAME "${FILE}" ABSOLUTE)
# 获取文件父路径
get_filename_component(PARENT_DIR "${FULL_NAME}" PATH)
# 移除父路径中的源码根路径
string(REPLACE "${ARGV0}" "" GROUP "${PARENT_DIR}")
# 确保路径使用windows路径符号
string(REPLACE "/" "\" GROUP "${GROUP}")
# 将文件归组到 "Source Files" 和 "Header Files"
if("${FILE}" MATCHES ".*\.h")
set(GROUP "Header Files${GROUP}")
else()
set(GROUP "Source Files${GROUP}")
endif()
source_group("${GROUP}" FILES "${FILE}")
endforeach()
endfunction(group_by_dir)
group_by_dir("${CMAKE_CURRENT_SOURCE_DIR}" ${INC_LIST})
group_by_dir("${CMAKE_CURRENT_SOURCE_DIR}" ${SRC_LIST})
12.判断操作系统平台及Win是否为32位
if(CMAKE_SYSTEM_NAME MATCHES "Linux") // 注意区分大写
message(STATUS "Linux platorm!")
elseif(CMAKE_SYSTEM_NAME MATCHES "Windows")
if(CMAKE_CL_64)
message(STATUS "Windows Win64 platform!")
else()
message(STATUS "Windows Win32 platform!")
endif(CMAKE_CL_64)
elseif(CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
message(STATUS "FreeBSD platform!")
else()
message(STATUS "other platform!")
endif(CMAKE_SYSTEM_NAME MATCHES "Linux")
13.执行生成后事件generation expression,如拷贝文件
add_custom_command(TARGET ${ProjectName}
POST_BUILD
COMMAND echo "$<TARGET_FILE_DIR:${project_name}>"
COMMAND ${CMAKE_COMMAND} -E make_directory ../bin
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${project_name}> ../bin/
)