文章目录
- 目的
- 一、原理
- 二、步骤
- 1.修改CMakeList
- 2.main函数如下
- 3.编译运行
目的
- 上一篇 学习了使用cmake 构建多源文件工程
- 在项目开发工程中,一般都会生成库文件或者调用其它的一些库文件,所以我们要学习一下简单生成和使用库文件
- 这里主要介绍
add_library
生成库文件,使用target_link_libraries
连接库文件
一、原理
-
在上一篇的基础上进行修改,目录结构如下
-
使用 add_library 把components 目录下的algo和math 源文件封成静态库,然后使用 target_link_libraries 连接生成的静态库,在main 中调用 生成库的接口,查看现象
二、步骤
1.修改CMakeList
代码如下(示例):
# cmake 最低要求版本 3.10,低于此版本将会报错
cmake_minimum_required(VERSION 3.10)# 设置工程名
project(prj_main)#添加头文件路径到 incs中
set(incs include components/match components/algo )#使用 add_library 生成的库,还是用其它路径下的库
set(USE_BUILD_LIB 1)#添加 要编译的源文件 到变量srcs中
# set(srcs main.c components/match/my_match.c )if (USE_BUILD_LIB)#生成库 components.a SHARED or STATICadd_library(components_lib STATIC components/match/my_match.c components/algo/bubble_sort.c)
endif()# 使用指定的源文件将可执行文件添加到项目中
add_executable(main_exe main.c)
target_include_directories(main_exe PUBLIC ${incs})if (USE_BUILD_LIB)#连接到生成的库 在.build 下target_link_libraries(main_exe PUBLIC components_lib)message(STATUS "use build components_lib")
else()#如果库文件 components_lib 不在默认的库搜索路径下,你可以使用(target_link_libraries 默认从build 目录连接)target_link_libraries(main_exe PUBLIC ${CMAKE_SOURCE_DIR}/lib/libcomponents_lib.a)message(STATUS "use lib libcomponents_lib")
endif()
- 使用 add_library(components_lib STATIC components/match/my_match.c components/algo/bubble_sort.c) 生成 components_lib 库
- 使用 target_link_libraries(main_exe PUBLIC components_lib) 连接 库
2.main函数如下
代码如下(示例):
#include <stdio.h>
#include "my_match.h"
#include "bubble_sort.h"
#include "main.h"
int main(void)
{int a = 123;int b = 456;int sort_arr[13] = {4, 5, 4, 3, 178, 4, 12, 54, 3, 15, 4, 35, 1};int sum = my_sum(a, b);//求和int max = CMP_GET_MAX(a, b);// 取最大值printf("sum=%d,max=%d \n", sum, max);bubbleSort(sort_arr, 13);// 排序printArray(sort_arr, 13);// 输出排序结果return 0;
}
- 其中 my_sum 、bubbleSort、printArray 是 components_lib 里面的接口
- 查看build 目录下可以看到生成的
libcomponents_lib.a
库文件,是 components_lib 上加了前缀lib和后缀.a
-
3.编译运行
代码如下(示例):
PS E:\test\TestCMake\cmake_test\3-add_lib\build> make
[ 20%] Building C object CMakeFiles/components_lib.dir/components/match/my_match.c.obj
[ 40%] Building C object CMakeFiles/components_lib.dir/components/algo/bubble_sort.c.obj
[ 60%] Linking C static library libcomponents_lib.a
[ 60%] Built target components_lib
[ 80%] Building C object CMakeFiles/main_exe.dir/main.c.obj
[100%] Linking C executable main_exe.exe
[100%] Built target main_exe
PS E:\test\TestCMake\cmake_test\3-add_lib\build> .\main_exe.exe
sum=579,max=456
1 3 3 4 4 4 4 5 12 15 35 54 178
- 结果输出 求和结果和取最大结果sum=579,max=456 ,
- 排序结果:1 3 3 4 4 4 4 5 12 15 35 54 178