一.静态库和动态库的简述
当我们想把代码提供给别人用,又不想被别人看自己的代码时,我们就可以建立自己的程序函数库。程序函数库是一些已经编译好的代码和数据,我们人是很难看懂的。
在Linux中程序函数库分为:静态函数库以.a后缀结尾、动态函数库(共享函数库).以.os结尾。
静态库的特点:
①在程序执行前加载进去的
②相对于加载动态库,程序执行比较快。
③不同程序执行,使用相同函数库时,每次都会加载一份静动态库进内存,会造成资源浪费。
动态库的特点:
①在程序执行时加载进去的
②不同程序执行,使用相同函数库时,只需要加载一份动态库进内存。
二.静态函数库的生成和使用:
1.生成
①生成.o文件
pi@raspberrypi:~/zlt/static $ gcc funs.c -o funs.o -c
pi@raspberrypi:~/zlt/static $ ls
config.h funs.c funs.o main.c //config.h是funs.c函数的声明
②通过ar工具将目标文件打包成.a静态库文件,要以lib
pi@raspberrypi:~/zlt/static $ ar rcs libfuns.a funs.o
pi@raspberrypi:~/zlt/static $ ls
config.h funs.c funs.o libfuns.a main.c
r c s参数的意义:
r - replace existing or insert new file(s) into the archive
c - do not warn if the library had to be created
s - create an archive index (cf. ranlib)
2,静态库的使用
pi@raspberrypi:~/zlt/static $ gcc main.c -lfuns -L ./
pi@raspberrypi:~/zlt/static $ ls
a.out config.h funs.c funs.o libfuns.a main.c
-l 表示链接静态库
-L表示指定静态库的路径
三.动态库的生成和使用
1.动态库的生成
①生成.o文件
pi@raspberrypi:~/zlt/dynamic $ gcc funs.c -o funs.o -c -fPIC
pi@raspberrypi:~/zlt/dynamic $ ls
config.h funs.c funs.o main.c
-fpic是一种标准,作用于编译阶段,在生成文件时使用该标准,以生成位置无关的代码。
②生成.os文件
pi@raspberrypi:~/zlt/dynamic $ gcc funs.o -shared -o libfuns.os
pi@raspberrypi:~/zlt/dynamic $ ls
config.h funs.c funs.o libfuns.os main.c
-shared 指定生成动态库。
2.动态库的使用
pi@raspberrypi:~/zlt/dynamic $ gcc main.c -lfuns -L ./