有些日子没写博客了,今天又要开始“创作”了,写一篇跨平台的工程构建工具CMake的学习笔记,方便以后随时查看回顾
简介
- 背景
CMake是kitware公司以及一些开源开发者在开发几个工具套件(VTK)过程的衍生品,最终形成体系,成为一个独立的开源项目,项目诞生于2001年,其官网是https://cmake.org/ 帮助文档是https://cmake.org/documentation/ - 特点
- 开源,使用BSD许可发布
- 跨平台,可生成native编译配置文件,在Linux/Unix平台,生成Makefile文件;在macOS平台,生成Xcode工程;在Windows平台,生成MSVC工程文件
- 能够管理大型项目,例:KDE4
- 简化编译构建过程和编译过程,只需要 cmake + make
- 效率高
- 可扩展,可以为CMake编写特定功能的模块,扩充CMake功能
构建CMake “hello world”
1. 内部构建
- 创建源文件和构建定义文件
#!/bin/bash
mkdir cmake_test1
cd cmake_test1
touch main.cpp
touch CMakeLists.txt #创建CMake的构建定义文件,文件名大小写敏感
- 编辑源代码
//main.cpp
#include <iostream>
int main() {
std::cout << "hello world" << std::endl;
return 0;
}
- 编辑构建定义文件(指令是大小写无关的,参数是有关的)
#CMakeLists.txt
#指明对 CMake 最低版本的要求(对版本没有特殊要求可以省略)
cmake_minimum_required(VERSION 3.10.0)
#定义工程名称,并可指定工程支持的语言,支持的语言列表是可以忽略的,默认情况表示支持所有语言
project(HELLO)
#显式定义变量,如果有多个源文件,可以在 main.cpp 后面追加,可以用空格 " " 或分号隔开 ";"
set(SRC_LISTS main.cpp)
#定义了这个工程会生成一个文件名为 hello 的可执行文件,相关的源文件是 SRC_LISTS 中定义的源文件列表,在这里可以直接写成 add_executable(hello main.cpp)
#另外需要注意的是作为工程名的 HELLO 和生成的可执行文件 hello 是没有任何关系的
add_executable(hello ${SRC_LISTS})
- 开始构建
#在当前目录构建对应平台的编译配置文件
cmake .
#输出下面的信息
-- The C compiler identification is AppleClang 12.0.0.12000032
-- The CXX compiler identification is AppleClang 12.0.0.12000032
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/liuwenlong/Downloads/code/cmake_proj/cmake_test1
生成CMakeCache.txt等中间文件,还有一个Makefile文件
- 编译
#编译
make
#输出下面的信息
Scanning dependencies of target hello
[ 50%] Building CXX object CMakeFiles/hello.dir/main.cpp.o
[100%] Linking CXX executable hello
[100%] Built target hello
生成了可执行文件hello
- 注意
- projectname_BINARY_DIR(指代编译路径)和projectname_SOURCE_DIR(指代工程路径)
cmake_minimum_required(VERSION 3.10.0)
#project 指令不仅定义工程名称,
#还隐式定义了两个 c