目录
使用场景
静态库:对空间要求较低,时间要求较高的核心程序中。
动态库:对时间要求较低,对空间要求较高。
静态库制作及使用
将.c文件生成.o文件
gcc -c aaa1.c -o aaa1.o
使用ar工具制作静态库
ar rcs lib库名.a aaa1.o aaa2.o aaa3.o
编译静态库到可执行文件中
gcc xxx.c lib库名.a -o xxx -I 头文件路径
动态库制作及使用
将.c文件生成.o文件,生成位置无关的代码 -fPIC
gcc -c a1.c -o a1.o -fPIC
使用gcc -share制作动态库
gcc -share -o lib库名.so a1.o a2.o a3.o
编译可执行程序时,需要指定所使用的动态库。-l:指定库名。-L:指定库路径。-I:头文件路径。
gcc xxx.c -o xxx.out -l 库名 -L 路径 -I 头文件路径
运行报错
./xxx.out
./main.out
原因
链接器:工作于链接阶段,工作时需要-l和-L。
动态链接器:工作于程序运行阶段,工作时需要提供动态库所在目录位置。
解决
临时解决:
修改环境变量,终端重启,环境变量失效。
export LD_LIBRARY_PATH=动态库路径
永久解决:
写入终端配置文件,使用绝对路径。
vim ~/.bashrc
重启终端,让动态库生效。
拷贝动态库解决:
将动态库拷贝到/lib目录下。(标准C库所在目录位置)
配置文件解决:
sudo vim /etc/ld.so.conf
使配置文件生效
sudo ldconfig -v
查看动态库链接信息
ldd xxx.out
测试代码
a1.c
int a1_Ku(int a,int b){
return a+b;
}
a2.c
int a2_Ku(int a,int b){
return a-b;
}
a3.c
int a3_Ku(int a,int b){
return a*b;
}
a_Ku.h
#ifndef _A_KU_H_
#define _A_KU_H_
int a1_Ku(int a,int b);
int a2_Ku(int a,int b);
int a3_Ku(int a,int b);
#endif
main.c
#include <stdio.h>
#include "a_Ku.h"
int main(){
int a=10;
int b=2;
printf("a1:%d\n",a1_Ku(a,b));
printf("a2:%d\n",a2_Ku(a,b));
printf("a3:%d\n",a3_Ku(a,b));
return 0;
}