目录
1.为什么CMake
cmake 可用于跨平台、开源的构建系统。
它是一个集软件构建、测试、打包于一身的软件。
它使用与平台和编译器独立的配置文件来对软件编译过程进行控制。
2. 案例使用说明
2.1 简单文件编译
/*simple.c*/
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
printf("hello cmake\n");
return 0;
}
project(simple)
add_executable(simple simple.c)
编译 操作指令如下:

新建 build 的目的,在于 让编译生成的文件与 源文件隔开;
使用 cmake .. 这里的.. 表示去上层目录查找 CMakeLists.txt文件;
可以看到 编译出了可执行固件 simple

运行可以得到可执行结果。
2.2 多文件多目录编译
目录结构

源码说明
/*main.c*/
#include <stdio.h>
#include "math/math_add.h"
int main(void)
{
int res = math_add(1,2);
printf("add result is :%d \n",res);
return 0;
}
和main.c同级别的 CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(complicate)
aux_source_directory(. DIR_SRCS)
add_subdirectory(math) #add sub directory
add_executable(complicate ${DIR_SRCS})
target_link_libraries(complicate mathlib)
/*math_add.c*/
#include "math_add.h"
int math_add(int a,int b)
{
return (a+b);
}
#ifndef MATH_ADD_H__
#define MATH_ADD_H__
int math_add(int a,int b);
#endif
同级的CMakeLists.txt
aux_source_directory(. DIR_LIB_SRCS)
add_library(mathlib ${DIR_LIB_SRCS})
编译指令

得到运行结果:

2.3 进阶使用
目录结构
|---example_person.cpp
|---CMakeLists.txt
|---proto_pb2
|--Person.pb.cc
|--Person.pb.h
|--CMakeLists.txt
|---proto_

本文详细介绍了CMake的使用,从基本的单文件编译到复杂的多文件多目录项目,再到进阶的配置技巧。通过案例展示了如何设置CMakeLists.txt文件,包括添加源文件、链接库、设置编译选项等。此外,还列举了CMake常用语法和命令,如项目设置、文件搜索、库链接等,帮助开发者更好地理解和应用CMake进行跨平台构建。
最低0.47元/天 解锁文章
903

被折叠的 条评论
为什么被折叠?



