静态函数库名字一般是:libxxx.a (xxx为库的名字)。
动态函数库名字一般是:libxxx.so (xxx为库的名字)。
*静态库是以空间换时间,动态库是以时间换空间。
*linux系统的函数库目录一般为:/lib、/usr/lib。
1.静态库的制作
① 准备测试文件:
// 源文件 add.c
#include <stdio.h>
#include "head.h"
int add(int a, int b)
{
return a+b;
}
// 源文件 mult.c
#include <stdio.h>
#include "head.h"
int max(int a, int b)
{
return (a > b)?a:b;
}
// 头文件 head.h
#ifndef _HEAD_H
#define _HEAD_H
// 加法
int add(int a, int b);
// 求最大值
int max(int a, int b);
#endif
// 测试程序 test.c
#include <stdio.h>
#include "head.h"
int main()
{
int a = 30;
int b = 50;
printf("a = %d, b = %d\n", a, b);
printf("a + b = %d\n", add(a, b));
printf(max = %d\n", max(a, b));
return 0;
}
② 将源文件 add.c, mult.c 进行汇编,得到二进制目标文件(汇编文件 *.o) add.o, mult.o。
#gcc -c *c.
③ 执行 ar -crs libxxx.a *.o
。
ar命令:
ar命令可以用来创建、修改库,也可以从库中提出单个模块。ar是archiver的缩写。
-r -->将文件插入库文件中,如果已经存在会直接替换。
-t -->显示库文件中所包含的.o文件。
-c -->表示create,创建;
xxxx–>表示库的名字
④ 编译执行 test.c。
-L. -->gcc链接库的存放路径,-L后面的“.”表示当前目录(如果你把制作的库放在/lib、/usr/lib等目录下,可不需要该选项)。
-I. -->指定程序要链接的库名。
*或将库文件复制到系统库目录中,如 /lib/。(!不推荐)
编译后链接静态库的程序就好了,此时删除静态库对程序不会造成影响。
2.动态库的制作
① 准备测试文件。(与静态库操作①一致)
② 将相应.c文件转换成汇编文件.o。
#gcc -fPIC *.c -c
// -fPIC -->产生位置无关代码
③ 创建动态库
#gcc -shared -o libxxxx.so *.o
// -shared -->表示动态库(共享库)
// xxxx -->表示动态库的名字
*以上两步可以合并为一步:
#gcc -fPIC -shared -o libxxxx.so *.c
④ 编译 test.c
#gcc -o main main.c -L. -lxxxx
⑤ 执行 test 程序
此时直接执行:./test 会报错。
可以将才制作的动态库放在/usr/lib/下,但不推荐。
一般使用语句export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:你指定的目录