Cmake构建自动化编译环境
完整项目文件结构:
一个完整的项目应该包括如下文件结构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| ProjectName/ ├── CMakeLists.txt ├── src/ │ ├── main.cpp │ ├── xxx.cpp │ └── yyy.cpp ├── include/ │ ├── xxx.h │ └── yyy.h │── build/ │── lib/ └── test/example/ ├── thridparty/ ├── README.md └── autobuild.sh
|
- bin:生成的可执行文件
- lib:生成的中间库文件
- include:
- src:
- build:编译过程中产生的临时文件
- test/example:示意文件
- thridparty:第三方库文件
- CMakeLists.txs:
- autobuild.sh:一键编译,其实就是执行的cmake文件
- license:
- readme:
ChatServer文件结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| ChatServer/ ├── .vscode/ ├── src/ │ ├── server │ │ ├── chat_server.cpp │ │ └── CmakeLists.txt │ │ │ └── client │ ├── chat_client.cpp │ └── CmakeLists.txt ├── include/ │ ├── chat_server.h │ ├── chat_client.h │ └── otherfile.h ├── build/Makefile ├── bin/ │ └── 生成的可执行文件 ├── thridparty/ │ └── json.hpp ├── test/ ├── CMakeLists.txt ├── README.md └── autobuild.sh
|
CMakeLists.txt文件解释
从顶层开始,每一个子目录下都有自己的CMakeLists.txt文件.下面是每一层的CMakeLists.txt文件,非常不完善,正在补充中…
- 顶层CMakeLists,路径:chatserver/CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| cmake_minimum_required(VERSION 3.0) project(chat)
# 配置编译选项 set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -g)
# 添加子目录
#配置最终的可执行文件的输出路径,PROJECT_SOURCE_DIR表示当前项目的根目录 set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
#配置头文件的搜索路径 include_directories(${PROJECT_SOURCE_DIR}/include) include_directories(${PROJECT_SOURCE_DIR}/include/server)
#加载子目录,子目录下也需要有CMakeLists.txt文件,子目录都写在src文件下 add_subdirectory(src)
|
- src中CMakeLists,路径:chatserver/src/CMakeLists.txt
1 2
| #添加子目录,在server目录下也有一个CMakeLists.txt文件 add_subdirectory(server)
|
- src/server中CMakeLists,路径:chatserver/src/server/CMakeLists.txt
1 2 3 4 5 6
| #定义了一个SRC_LIST变量,包含当前目录下所有的源文件 aux_source_directory(. SRC_LIST) #由所有源码生成可执行文件,指定生成可执行文件的名称为ChatServer add_executable(ChatServer ${SRC_LIST}) #指定可执行文件需要链接时所依赖的库,muduo_net muduo_base pthread target_link_libraries(ChatServer muduo_net muduo_base pthread)
|
- src/client中CMakeLists,路径:chatserver/src/client/CMakeLists.txt
1 2 3 4 5 6 7
| # 定义了一个SRC_LIST变量,包含了该目录下所有的源文件 aux_source_directory(. SRC_LIST)
# 指定生成可执行文件 add_executable(ChatClient ${SRC_LIST}) # 指定可执行文件链接时需要依赖的库文件 target_link_libraries(ChatClient pthread)
|
执行命令:cmake . 或者 cmake ..
在哪里执行cmake,就会在哪里生成中间文件和可执行文件
因此可以进入build目录执行cmake ..命令,这样生成的文件就在build目录下
未完待续…