[linux专题]CMakeLists 使用案例详解

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1.为什么CMake

2. 案例使用说明

2.1 简单文件编译

2.2 多文件多目录编译

 2.3 进阶使用

3.CMake常用语法

3.1 常用模板

3.2 常用命令


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_buf
        |---General_buf_read.h
        |---General_buf_w
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值