Linux函数库分类:
1) 静态库
a) 定义
静态库就是一些.o目标文件的集合,以.a结尾。静态库在程序链接的时候使用,
链接器会将程序中使用到函数的代码从库文件中拷贝到可执行文件中。一旦链接完成,在执行
程序的时候就不需要静态库了。由于每个使用静态库的应用程序都需要拷贝所用函数的代码,
所以生成的可执行文件会比较大。
b) 创建和应用(包括hello.h, hello.c, hello_test.c)
* 在include目录中创建头文件hello.h
void hello(); //声明函数原型
* 创建源文件hello.c
#include <stdio.h>
#include "hello.h"
void hello()
{
printf("hello, welcome to library world!\n");
}
* 制作hello.o的静态库文件libhello.a
gcc -o hello.o -Iinclude -c hello.c
ar rcs libhello.a hello.o
注: rcs中的r表明将模块hello.o加入到静态库中,c表示创建静态库,s表示生产索引。
* 创建测试/调用程序hello_test.c
#include <stdio.h>
#include "hello.h"
int main(void)
{
printf("use library hello.\n");
hello();
return 0;
}
* 编译和链接生成可执行文件
gcc -o hello_test.o -Iinclude -c hello_test.c
gcc -o hello_static hello_test.o -L. -lhello
或者
gcc -o hello_static -Iinclude hello_test.c -L. -lhello
注:
* -L.参数表示将当前目录加入到库搜索路径,默认的库搜索路径
在/usr/lib目录下。
* -I参数表示搜索头文件的路径,这样gcc在查找头文件的时候会
首先到存放源文件的目录中查找,若没有再从-I指定的目录查找
* -lname参数表示库搜索目录下的libname.a 或libname.so文件
这也是为什么库文件都以lib开头的原因之一,如果你的库文件
不是libhello.a,而是hello.a 那就不能用-l参数
而是直接写上hello.a
可以这样gcc -o hello_static hello_test.o -L. hello.a
* gcc -L. -lhello hello_test.o -o hello_static会出错。原因是
-l是链接器选项,必须要放到被编译文件hello_test.o的后面。
* 运行hello_static
./hello_static
注: rm libhello.a
./hello_static
结果是没有任何影响
2) 共享库(动态库/动态链接库-->linux中以.so为后缀,windows中以.dll为后缀)
a) 定义
共享库以.so结尾(so == share object),在程序的链接时候并不像静态库那样在
拷贝使用函数的代码,而只是作些标记。然后在程序开始启动(实际上在加载程序时)运行的时候,
加载所需的函数。所以应用程序在运行的时候仍然需要共享库的支持。
共享库链接出来的文件比静态库要小得多。C语言中所有的共享库放置在
/usr/lib目录中。
b) 创建和应用
* 创建头文件hello.h
void hello();
* 创建源文件hello.c
#include <stdio.h>
#include "hello.h"
void hello()
{
printf("hello, welcome to library world!\n");
}
* 制作hello.o的共享库文件libhello.so
gcc -o hello.o -Iinclude -c hello.c
gcc -shared -fPCI -o libhello.so hello.o (GCC 4.6.1中使用-fPCI而不是-fPCI)
注: -shared 表明是使用共享库
-fpci或者-fPCI表明创建产生独立目标代码,
具体应用取决于平台
* 创建测试/调用程序hello_test.c
#include <stdio.h>
#include "hello.h"
int main(void)
{
printf("use library hello.\n");
hello();
return 0;
}
* 编译和链接生成可执行文件
gcc -o hello_test.o -Iinclude -c hello_test.c
gcc -o hello_share hello_test.o -L. -lhello
或者
gcc -o hello_share -Iinclude hello_test.c -L. -lhello
* 运行hello_share
./hello_share
出错解决:
* cp libhello.so /usr/lib
* export LD_LIBRARY_PATH=.
* 修改/etc/ld.so.conf文件,把库所在的路径加到文件末尾,并执行ldconfig刷新
注: rm /usr/lib/libhello.so
./hello_share
结果是出现找不到库文件的错误