一、介绍
1、什么是库?
库是一种可执行代码的二进制格式,能够被载入到内存中执行。程序函数库可分为3种类型:静态函数库(static libraries)、共享函数库(shared libraries)、动态加载函数库(dynamically loaded libraries)。
2、静态库(.a、.lib)
静态函数库在程序执行(编译)前就加入到应用程序中去。
特点:
- 静态库被打包到应用程序中加载速度快;
- 发布程序无需提供静态库,已经编译到应用程序中,移植方便 (发布=程序);
- 链接时完整的拷贝到可执行文件中,被多次使用就有多份多余的拷贝;
- 更新、部署、发布麻烦。
3、动态库(.so、.dll)
动态函数库和共享函数库是同一个东西(在Linux上叫共享对象库,文件后缀是.so ,windows上叫动态加载函数库,文件后缀是.dll)。
动态函数库在程序执行时动态(临时)加入到应用程序中去。
Linux中命名系统中共享库的规则
特点:
- 链接时不复制,程序运行时由系统动态加载到内存,供程序调用,系统只加载一次,多个程序可以共用,节省内存;
- 加载速度比静态库慢;
- 程序升级简单,因为应用程序里面没有库的源代码,升级之后只要库的名字不变,函数名以及参数不变,只是实现做了优化,就能加载成功;
- 发布程序需要提供依赖的动态库(发布 = 程序 + 动态库)。
二、静态库生成与使用
// 接口文件config.h
#ifndef _CONFIG_H
#define _CONFIG_H
int plus(int a, int b);
int minus(int a, int b);
#endif
// 源文件plus.c
int plus(int a, int b)
{
return a + b;
}
// 源文件minus.c
int minus(int a, int b)
{
return a - b;
}
// 主程序main.c
#include <stdio.h>
#include "config.h"
int main()
{
int a = 0;
int b = 0;
printf("a = ");
scanf("%d", &a);
printf("b = ");
scanf("%d", &b);
printf("%d + %d = %d\n", a, b, plus(a, b));
printf("%d - %d = %d\n", a, b, minus(a, b));
return 0;
}
1、生成
静态库格式:xxx.a 或 xxx.lib
第一步:生成.o文件 gcc xxx.c -c
例:gcc plus.c -c文件 (仅源文件生成.o文件,主程序不用生成.o文件)
第二步:打包.o文件生成静态库 ar rcs 静态库名字.a 所有需要打包的.o文件
例:ar rcs libtext.a plus.o minus.o (库名字尽量由lib开头)
2、使用
生成可执行文件:gcc main.c -ltext -L ./ -o mainProStatic
-ltext: -l指定要用的静态库,库名砍头(lib)去尾(.a)。
-L:告诉gcc编译器从-L指定的路径去找静态库。如不指定,默认是从/usr/lib 或 /usr/local/lib 去找。
需要注意的是:如果库文件和C文件都在同一目录下,则可以不使用 -l 、-L去指定库,动态库也一样,格式是:
gcc main.c libtext.a -o main
三、动态库生成与使用
// 接口文件config.h
#ifndef _CONFIG_H
#define _CONFIG_H
int plus(int a, int b);
int minus(int a, int b);
#endif
// 源文件plus.c
int plus(int a, int b)
{
return a + b;
}
// 源文件minus.c
int minus(int a, int b)
{
return a - b;
}
// 主程序main.c
#include <stdio.h>
#include "config.h"
int main()
{
int a = 0;
int b = 0;
printf("a = ");
scanf("%d", &a);
printf("b = ");
scanf("%d", &b);
printf("%d + %d = %d\n", a, b, plus(a, b));
printf("%d - %d = %d\n", a, b, minus(a, b));
return 0;
}
1、生成
动态库格式:xxx.so 或 xxx.dll
生成动态库:gcc -shared -fpic -o 动态库名字.so 所有需要的源文件
-shared: 指定生成动态库。
-fpic: 作用于编译阶段,在生成目标文件时使用,以生成位置无关的代码。
例:gcc -shared -fpic -o libtext.so minus.c plus.c (库名字尽量由lib开头)
2、使用
生成可执行文件:gcc main.c -ltext -L ./ -o mainProDy
-ltext: -l指定要用的动态库,库名砍头(lib)去尾(.so)。
-L:告诉gcc编译器从-L指定的路径去找动态库。如不指定,默认是从/usr/lib 或 /usr/local/lib 去找。
加载动态库时: Linux的动态库默认搜索路径为/usr/lib与/usr/local/lib ,如果动态库(.so)没放在/usr/lib与/usr/local/lib下,搜索找不到程序,运行就会出错,所以在运行程序前要指定动态库的搜索路径。
指定动态库搜索路径:
方法1:
在当前的终端命令行输入:export LD_LIBRARY_PATH=“路径名”(但该方式仅对当前的终端有效)。
方法2:
编写一个shell脚本,进行添加环境变量和运行程序:
start.sh
export LD_LIBRARY_PATH="/home/CLC/demo"
./mainProDy
给脚本加个可执行权限
chmod +x start.sh