如何创建和使用,简而言之看代码,从例子入手:
/*
* unsgn_pow.c
*
* Created on: 2012-7-16
* Author: liwei.cai
*/
//库函数
unsigned long long unsgn_pow(unsigned int x , unsigned int y)
{
unsigned long long res = 1;
if (y == 0)
{
res = 1;
}
else if(y == 1)
{
res = x;
}
else
{
res = x * unsgn_pow(x, y-1);
}
return res;
}
/*
* pow_test.c
*
* Created on: 2012-7-16
* Author: liwei.cai
*/
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
unsigned int x, y;
unsigned long long res;
if ((argc < 3) || (sscanf(argv[1], "%u", &x) != 1) ||
(sscanf(argv[2],"%u", &y) != 1))
{
printf("Usage: pow base exponent\n");
exit(1);
}
res = unsgn_pow(x, y);
printf("%u ^ %u = %u\n",x, y, res);
exit(0);
}
首先,将库函数编译成目标文件;使用归档工具ar将一些目标文件集成在一起。
# gcc -c unsgn_pow.c
# ar rcsv libpow.a unsgn_pow.o
然后,编译主程序,连接刚生成的静态库libpow.a
# gcc -o pow_test pow_test.c -L . -lpow
# ./pow_test 2 10
说明:选项"-L dir" 功能与“-I dir ”类似, 能够在库文件的搜索路径列表中添加dir目录, 而“-lname”选项指示编译时连接到的库函数文件 libname.a或者libname.so
下面是创建和使用动态库,看代码
# gcc -fPIC -Wall -c unsgn_pow.c
# gcc -shared -o libpow.so unsgn_pow.o
# gcc -o pow_test pow_test.c -L . -lpow
在程序执行之前,需要注册动态库的路径名。有几种方法:修改/etc/ld.so.conf文件,或者修改LD_LIBRARY_PATH环境变量,或者将库文件直接复制到/lib或者/usr/lib目录下。
说明:动态库只有当使用它的程序执行时才被链接使用,而不是将需要的部分直接编译到可执行文件中,并且一个动态库可以被多个程序使用,故称共享库。而静态库会整合到程序中,因此在程序执行时不用加载静态库,从而可知,链接到静态库的会使程序臃肿,并且难以升级,但是可能会比较容易部署。而链接到动态库会使程序轻便,并且容易升级,但是会难以部署。