目录
🌞1. Linux下静态库和动态库的基本概念
对.h头文件的理解 传送门:【头文件】对.h文件的理解-CSDN博客
🌞2. 动态库
🌊2.1 动态库如何生成
下面通过一个小栗子介绍如何生成一个动态库。
🌍2.1.1 文件详情
我在路径/root/host/my_program/asoc/include下创建四个文件
一个头文件:
vi so_test.h
#ifndef SO_TEST_H
#define SO_TEST_H
int addTwoiNum(int a, int b);
int subTwoiNum(int a, int b);
int mulTwoiNum(int a, int b);
#endif
三个.c文件:
vi so_test_a.c
#include "so_test.h"
#include <stdio.h>
int addTwoiNum(int a, int b) {
return a + b;
}
vi so_test_b.c
#include "so_test.h"
#include <stdio.h>
int subTwoiNum(int a, int b) {
return a - b;
}
vi so_test_c.c
#include "so_test.h"
#include <stdio.h>
int mulTwoiNum(int a, int b) {
return a * b;
}
🌍2.1.2 编译生成动态库
给文件附上权限:
chmod 777 so_test_a.c so_test_b.c so_test_c.c so_test.h
接下来,我们将编译这些文件成一个动态库。
在Linux系统中可以使用gcc
来完成这个任务。
gcc -c -Wall -Werror -fpic so_test_a.c so_test_b.c so_test_c.c
gcc -shared -o libtest.so so_test_a.o so_test_b.o so_test_c.o
现在,会得到一个名为 libtest.so
的动态库文件。
🌊2.2 动态库如何使用
前面已经成功生成了一个动态链接库libtest.so,下面通过一个程序来调用这个库里的函数。
比如程序的源文件为:main.c【我创建的目录是/root/host/my_program/asoc/my_program】
#include <stdio.h>
#include "so_test.h"
int main() {
int result_a, result_b, result_c;
int x = 10, y = 5;
// 调用动态库中的函数
result_a = addTwoiNum(x, y);
result_b = subTwoiNum(x, y);
result_c = mulTwoiNum(x, y);
// 打印结果
printf("Result of add: %d\n", result_a);
printf("Result of sub: %d\n", result_b);
printf("Result of mul: %d\n", result_c);
return 0;
}
现在需要链接 libtest.so
到源文件。
🌍2.2.1 案例
【案例】如果头文件路径是 /root/host/my_program/asoc/include/so_test.h
,动态库文件路径是 /root/host/my_program/asoc/include/libtest.so
,可以这样编译 main.c
文件:
链接完成会生成一个 main 的可执行文件,这个可执行文件到底有没有成功链接到动态链接库呢?
可以使用下面的命令来查看:
ldd main
这里说明虽然我们已经使用 -L
选项指定了库文件的搜索路径,但是系统加载器在搜索动态库时还是会按照默认的路径 /lib 或者 /usr/lib 的路径进行搜索,因此即使编译成功,但运行时仍找不到动态库。
要解决这个问题,可以尝试设置 LD_LIBRARY_PATH
环境变量来指定动态库的搜索路径。例如我的动态库.so是在路径/root/host/my_program/asoc/include下,则使用命令:
LD_LIBRARY_PATH=/root/host/my_program/asoc/include ./main
这样运行时就能够找到动态库 libtest.so+运行成功!
🌍2.2.2 动态库错误记录
🌞3. 静态库
🌊3.1 静态库如何生成
下面通过一个小栗子介绍如何生成一个静态库。
🌍3.1.1 文件详情
我在路径/root/host/my_program/asoc/include下创建下面的文件
vi staticlib.h
#ifndef __STATICLIB_H
#define __STATICLIB_H
int hello();
#endif
vi staticlib.c
#include "staticlib.h"
#include <stdio.h>
int hello(){
printf("hello,this is static lib\n");
return 0;
}
🌍3.1.2 编译生成动态库
给文件附上权限:
chmod 777 staticlib.h staticlib.c
使用编译器将 staticlib.c
编译成目标文件(.o
文件):
gcc -c staticlib.c -o staticlib.o
使用 ar
命令将目标文件打包成静态库文件 libstatic.a
:
ar rcs libstatic.a staticlib.o
这样就生成了名为 libstatic.a
的静态库文件,其中包含了 staticlib.o
的内容。
🌊3.2 静态库如何使用
前面已经成功生成了一个动态链接库libtest.so,下面通过一个程序来调用这个库里的函数。
比如程序的源文件为:test.c【我创建的目录是/root/host/my_program/asoc/my_program】
内容如下:
#include <stdio.h>
#include "staticlib.h"
int main() {
printf("Calling hello() function...\n");
hello();
return 0;
}
接下来,需要编译 main.c
并链接静态库 libstatic.a
。
gcc test.c -o test -I/root/host/my_program/asoc/include/ -L/root/host/my_program/asoc/include/ -lstatic
然后运行可执行文件 test
:
./test
说明静态库链接成功!