這是我在學習使用CMake時記錄的筆記,主要參考《CMake Cookbook》這本書。
用CMake編譯單源文件程序,示例程序如下:
#include <cstdlib>
#include <iostream>
#include <string>
std::string say_hello() { return std::string("Hello, CMake world!"); }
int main() {
std::cout << say_hello() << std::endl;
return EXIT_SUCCESS;
}
CMakeLists.txt 如下:
# CMake 版本要求
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
# 聲明項目名稱及語言
project(recipe-01 LANGUAGES CXX)
# 指導CMake創建目標程序
add_executable(hello-world hello-world.cpp)
構建命令:
mkdir -p build
cd build
cmake ..
# 以上三項等價於 cmake -H. -Bbuild
cmake --build .
cmake -H. -Bbuild
中的-H.
意味着在當前文件夾中查找CMakeList.txt
文件,-Bbuild
意味着在build
文件夾中生成編譯所需的文件。該命令還在標準化中所以更建議使用傳統的方式。
在創建的build
文件夾下有以下文件:
- Makefile:指導make構建工程的配置文件。
- CMakeFiles:存放臨時文件,CMake在探測操作系統、編譯器等的時候產生的臨時文件。除此之外,根據所選生成器(在Unix類系統中是Unix Makefiles generator,在Windows上默認是Visual Studio)的不同,也會包含項目相關的文件。
- cmake_install.cmake:包含安裝規則的CMake腳本,在安裝時使用。
- CMakeCache.txt:CMake緩存
cmake --build .
是一個跨平臺的命令,會調用平臺原生的構建命令,在linux中調用make。
構建選項
在這個例子中的構建目標只有hello-world
這個可執行文件,但其實cmake支持更多構建選項。運行命令cmake --build . --target help
可以看到可用的構建項:
$ cmake --build . --target help
The following are some of the valid targets for this Makefile:
... all (the default if no target is provided)
... clean
... depend
... rebuild_cache
... hello-world
... edit_cache
... hello-world.o
... hello-world.i
... hello-world.s
這些構建選項可以通過cmake --build . --target <target-name>
生成。
- all (在VS生成器中爲ALL_BUILD)爲默認構建選項,將構建項目中的所有目標
- clean 清除所有生成的文件
- depend 調用CMake爲源代碼生成依賴項
- rebuild_cache 調用CMake重建CMakeCache.txt。這在源中添加了新的條目時需要用到。
- edit_cache 允許直接編輯緩存條目
對於有測試環節以及安裝規則的更加複雜的工程,CMake會生成以下額外構建選項
- test (在VS生成器中爲RUN_TESTS)將在CTest的支持下運行測試樣例
- install 運行項目的安裝規則。
- package 調用CPack爲該工程產生一個可以重新分發的包。
歡迎關注我的微信公衆號 江達小記