title: CMake实战一:单个源文件
categories:[实战一]
tags:[CMake]
date: 2021/12/23
作者:hackett
微信公众号:加班猿
CMake 反对大写、小写和大小写混合命令。
在 linux 平台下应用 CMake 生成 Makefile 并编译的流程如下:
- 编写 CMake 配置文件 CMakeLists.txt 。
- 执行命令
cmake PATH
或者ccmake PATH
生成 Makefile(ccmake
和cmake
的区别在于前者提供了一个交互式的界面)。其中,PATH
是 CMakeLists.txt 所在的目录。 - 应用
make
命令进行编译。 - 编译生成可执行程序运行
1、创立目录
mkdir cmakecd cmakemkdir demo1cd demo1
2、筹备好须要编译的文件
这里做个演示 所以就来个简略的代码,计算两个数的和,源文件为main.cpp
#include <stdio.h>#include <stdlib.h>int add(int a, int b) { return (a + b);}int main(int argc, char *argv[]) { if (argc < 3) { printf("Usage: %s argv[1] argv[2] \n", argv[0]); return 1; } int a = atof(argv[1]); int b = atoi(argv[2]); int result = add(a, b); printf("%d + %d = %d\n", a, b, result); return 0;}
3、编写CMakeLists.txt
编写 CMakeLists.txt 文件,并保留在与main.cpp
源文件同个目录下:
# CMake 最低版本号要求cmake_minimum_required (VERSION 2.8)# 我的项目信息project (demo1)# 指定生成指标add_executable(demo main.cpp)
CMakeLists.txt 的语法比较简单,由命令、正文和空格组成,其中命令是不辨别大小写的。符号 #
前面的内容被认为是正文。命令由命令名称、小括号和参数组成,参数之间应用空格进行距离。
对于下面的 CMakeLists.txt 文件,顺次呈现了几个命令:
cmake_minimum_required
:指定运行此配置文件所需的 CMake 的最低版本;project
:参数值是demo1
,该命令示意我的项目的名称是demo1
。add_executable
: 将名为main.cpp
的源文件编译成一个名称为 demo 的可执行文件。
4、编译我的项目
在main.cpp
当前目录下新建一个build
目录,进入build
目录执行cmake ..
,失去Makefile后再应用make
命令编译失去demo可执行文件
新建build目录是不便咱们清理cmake产生的缓存文件,不须要的时候间接删除build
目录即可
[root@hackett build]# cmake ..-- The C compiler identification is GNU 8.4.1-- The CXX compiler identification is GNU 8.4.1-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Check for working C compiler: /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: /usr/bin/c++ - skipped-- Detecting CXX compile features-- Detecting CXX compile features - done-- Configuring done-- Generating done-- Build files have been written to: /root/workspace/cmake/demo1/build[root@hackett build]# lsCMakeCache.txt CMakeFiles cmake_install.cmake Makefile[root@hackett build]# make[ 50%] Building CXX object CMakeFiles/demo.dir/main.cpp.o[100%] Linking CXX executable demo[100%] Built target demo[root@hackett build]# lsCMakeCache.txt CMakeFiles cmake_install.cmake demo Makefile[root@hackett build]# ./demo 2 32 + 3 is 5
如果你感觉文章还不错,能够给个"三连",文章同步到集体微信公众号[加班猿]
我是hackett,咱们下期见
参考文档:
CMake入门实战
CMake Tutorial