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

目录

1.为什么CMake

2. 案例使用说明

2.1 简单文件编译

2.2 多文件多目录编译

 2.3 进阶使用

3.CMake常用语法

3.1 常用模板

3.2 常用命令


1.为什么CMake

cmake 可用于跨平台、开源的构建系统

它是一个集软件构建、测试、打包于一身的软件。

它使用与平台和编译器独立的配置文件来对软件编译过程进行控制。

2. 案例使用说明

2.1 简单文件编译


/*simple.c*/
#include 
#include 

int main(void)
{
    printf("hello cmake\n");

    return 0;
}
project(simple)
add_executable(simple simple.c)

编译 操作指令如下:

[linux专题]CMakeLists 使用案例详解_第1张图片

 

新建 build 的目的,在于 让编译生成的文件与 源文件隔开;

使用 cmake ..   这里的.. 表示去上层目录查找 CMakeLists.txt文件;

可以看到 编译出了可执行固件 simple

 运行可以得到可执行结果。

2.2 多文件多目录编译

目录结构

[linux专题]CMakeLists 使用案例详解_第2张图片

源码说明

/*main.c*/
#include 
#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})

编译指令

[linux专题]CMakeLists 使用案例详解_第3张图片

得到运行结果:

 [linux专题]CMakeLists 使用案例详解_第4张图片

 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

你可能感兴趣的:(Linux,linux,cmake,CMakefile)