CMake基础篇(八)——构建更复杂的工程

前言:
   本篇文章介绍CMake如何构建更复杂的工程。

1 带有多个源文件

  如果一个工程有多个源文件需要编译,而源文件都在工程根目录下,只需要在CMake中增加源文件依赖的描述即可。目录结构如下。

1
2
3
4
5
6
7
8
╰─ tree
.
├── alg.c
├── alg.h
├── build
├── CMakeLists.txt
├── main.c
└── README.md

  main.c。

1
2
3
4
5
6
7
#include <stdio.h>
#include "alg.h"

void main(void)
{
printf("Sum = %d\n", Add(1, 2));
}

  alg.c。

1
2
3
4
5
6
#include "alg.h"

int Add(int Num1, int Num2)
{
return Num1 + Num2;
}

  alg.h。

1
extern int Add(int Num1, int Num2);

  CMakeLists.txt。

1
2
3
cmake_minimum_required(VERSION 3.0)
project(litchi)
add_executable(app main.c alg.c)

  在 add_executable 函数里添加列出所有源文件。如果一个目录下源文件非常多,一一列出过于繁琐,而且将来源文件的数量和名称可能变更,可以使用 aux_source_directory 函数自动搜索某个目录下的所有源文件,形成列表赋值到变量中。CMakeLists.txt改进后如下。

1
2
3
4
cmake_minimum_required(VERSION 3.0)
project(litchi)
aux_source_directory(. SRC_LIST)
add_executable(app ${SRC_LIST})

2 源码文件在不同路径

  通常项目的源码会根据框架设计、模块设计、类别等放到不同路径下。目录结构如下。

1
2
3
4
5
6
7
8
9
10
11
╰─ tree
.
├── build
├── CMakeLists.txt
├── inc
│ └── alg.h
├── main.c
├── main.h
├── README.md
└── src
└── alg.c

  CMakeLists.txt。

1
2
3
4
5
6
cmake_minimum_required(VERSION 3.0)
project(litchi)
include_directories(./inc)
aux_source_directory(. CUR_LIST)
aux_source_directory(src SRC_LIST)
add_executable(app ${CUR_LIST} ${SRC_LIST})

   include_directories 函数用于添加头文件路径, aux_source_directory 函数用于添加源文件路径,但一次只能一个路径。

1
2
3
4
5
6
7
8
9
10
11
12
cmake_minimum_required(VERSION 3.0)
project(litchi)
include_directories(.
./inc)

# Or
# include_directories(.)
# include_directories(./inc)

aux_source_directory(. CUR_LIST)
aux_source_directory(src SRC_LIST)
add_executable(app ${CUR_LIST} ${SRC_LIST})

  main.c。

1
2
3
4
5
6
7
8
#include <stdio.h>
#include "main.h"
#include "alg.h"

void main(void)
{
printf("Sum = %d\n", Add(1, N));
}

  main.c。

1
#define N 3

3 链接库文件

  CMake加载动态静态库很简单。目录结构如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
╰─ tree
.
├── build
├── CMakeLists.txt
├── inc
│ └── alg.h
├── lib
│ ├── build
│ │ ├── libDynLibName.so
│ │ └── libStcLibName.a
│ └── CMakeLists.txt
├── main.c
├── main.h
├── README.md
└── src
└── alg.c

  根目录下的 CMakeLists.txt 内容如下。

1
2
3
4
5
6
7
8
9
10
11
cmake_minimum_required(VERSION 3.0)
project(litchi)
include_directories(.
./inc)
aux_source_directory(. CUR_LIST)
# find_library(LIB_LIST libStcLibName.a ./
# ./lib/build)
find_library(LIB_LIST libDynLibName.so ./
./lib/build)
add_executable(app ${CUR_LIST})
target_link_libraries(app ${LIB_LIST})

   find_library 函数用于在指定路径下查找指定库文件,并将文件的绝对路径返回到变量第一个变量中。第二个参数是库文件名,库文件名可以不写后缀,默认是查找动态库文件,建议加上后缀(函数是根据后缀名来识别链接动态或静态库)。第三个参数是查找的路径。 target_link_libraries 函数用于连接库文件。