# 参考: https://www.hahack.com/codes/cmake/# CMake 最低版本号要求cmake_minimum_required (VERSION 2.8)# 项目信息project (hello)# [1]# 指定生成目标# 对于单个文件,只有写下面这一行。表示使用main.cpp生成可执行程序hello# ps: main.cpp 只是一个普通的hello world# add_executable(hello main.cpp)# [2]# 对于多个文件,如果在源文件中引用顺序正确,那么我们只要把所有引用文件写在后面即可# add_executable(hello main.cpp hello.cpp hello.h)# 目录结构如下# .# ├── build# ├── CMakeLists.txt# ├── hello.cpp# ├── hello.h# └── main.cpp# =============================================# [hello.cpp]# #include# void print()# {# printf("Hello \n");# }# =============================================# [hello.h]## #ifndef _HELLO_H# #define _HELLO_H# extern void print();# #endif# =============================================# [main.cpp]# #include # #include "hello.h"## using namespace std;# int main()# {# print();# return 0;# }# =============================================# [3]# 但是现在我们发现我们如果每次写一个文件就加一个源文件显然不合理# 当然是有集成写法到# 查找当前目录下的所有源文件# 并将名称保存到 DIR_SRCS 变量# aux_source_directory(. DIR_SRCS)# 指定生成目标# add_executable(hello ${DIR_SRCS})# =============================================# [4]# 多级别目录操作# 修改后目录如下,只简单修改了代码中到文件引用# .# ├── build# ├── CMakeLists.txt# ├── hello# │ ├── CMakeLists.txt# │ ├── hello.cpp# │ └── hello.h# └── main.cpp# 经过测试子目录到文件名不能和镜头库到名字冲突aux_source_directory(. DIR_SRCS)# 把子目录的CMakeList.txt引入add_subdirectory(hello)add_executable(sol main.cpp)# 添加链接库target_link_libraries(sol Test)# 在hello 目录下的CMakeList.txt如下# # 子目录中到CMakeList.txt# # 查找当前目录下的所有源文件# # 并将名称保存到 DIR_LIB_SRCS 变量# aux_source_directory(. DIR_LIB_SRCS)# # 生成链接库# add_library (Test ${DIR_LIB_SRCS})