# 参考: 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 <cstdio> # void print() # { # printf("Hello \n"); # } # ============================================= # [hello.h] # # #ifndef _HELLO_H # #define _HELLO_H # extern void print(); # #endif # ============================================= # [main.cpp] # #include <bits/stdc++.h> # #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})