参考: https://www.hahack.com/codes/cmake/

编写 CMakeLists.txt , 然后执行 cmake . 生成 Makefile

最后执行 make 生成可执行文件

# file: CMakeLists.txt

# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo1)

单个源文件

# 将名为 main.cc 的源文件编译成一个名称为 Demo 的可执行文件
add_executable(Demo main.cc)

多个源文件

add_executable(Demo main.cc MatchFunctions.cc)

# 或者

# 查找当前目录下的所有源文件 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
# 指定生成目标
add_executable(Demo ${DIR_SRCS})

多个目录 多个源文件

子目录和根目录下均需要编写 CMakeLists.txt

子目录中的文件可以编译成静态库

# file: subDir/CMakeLists.txt

# 查找当前目录下的所有源文件, 并将名称保存到 DIR_LIB_SRCS 变量
aux_source_directory(. DIR_LIB_SRCS)
# 生成链接库
add_library(MathFunctions ${DIR_LIB_SRCS})
# file: CMakeLists.txt

# 添加 match 子目录
add_subdirectory(subDir)

# 指定生成目标

# 添加链接库
target_link_libraries(Demo MathFunctions)

自定义编译选项

源代码: https://github.com/wzpan/cmake-demo/tree/master/Demo4