您的位置:首页 > 运维架构 > Linux

how to compile and link static/dynamic library in linux

2009-12-06 11:26 489 查看
for static library:

1) use gcc to compile the target files, for example:

gcc –c Strlen.c Strnlen.c

2) generates the static library with the following command:

ar –rc libstr.a Strlen.o Strnlen.o

3) how to use the static library

when we need to generate the executable code ( header files of the static library should be included )base on the static library, use the following commands[http://dev.csdn.net/article/84/84562.shtm]

gcc -o main1 -L/home/hcj/xxxxxxxx main.o libstr.a


中-I/home/hcj/xxxxxxxx和-L/home/hcj/xxxxxxxx是通过-I和-L指定对应的头文件和库文件的路径。
libstr.a是对应的静态库的名称。这样对应的静态库已经编译到对应的可执行程序中。执行对应的可执行文件便可以对应得函数调用的结果。

for the dynamic library, use the following commands:

[http://dev.csdn.net/article/84/84562.shtm]

gcc -fpic -shared -o libstr.so Strlen.c Strnlen.c

-fpic 使输出的对象模块是按照可重定位地址方式生成的。

-shared指定把对应的源文件生成对应的动态链接库文件libstr.so文件。

动态库的分为隐式调用和显式调用两种调用方法:

隐式调用的使用使用方法和静态库的调用差不多,具体方法如下:

gcc -c -I/home/hcj/xxxxxxxx main.c

gcc -o main1 -L/home/hcj/xxxxxxxx main.o libstr.so //这里是*.so

在这种调用方式中,需要维护动态链接库的配置文件/etc/ld.so.conf来让动态链接库为系统所使用,通常将动态链接库所在目录名追加到动
态链接库配置文件中。否则在执行相关的可执行文件的时候就会出现载入动态链接库失败的现象。在编译所引用的动态库时,可以在gcc采用
–l或-L选项或直接引用所需的动态链接库方式进行编译。在Linux里面,可以采用ldd命令来检查程序依赖共享库。

显式调用:

#include<dlfcn.h>

int (*pStrlenFun)(char* pStr); //声明对应的函数的函数指针

void *pdlHandle;

char *pszErr;

pdlHandle = dlopen("./libstr.so", RTLD_LAZY); //加载链接库/libstr.so

if(!pdlHandle)

{

printf("Failed load library/n");

}

pszErr = dlerror();

if(pszErr != NULL)

{

printf("%s/n", pszErr);

return 0;

}

//get function from lib

pStrlenFun = dlsym(pdlHandle, "Strlen"); //获取函数的地址

pszErr = dlerror();

if(pszErr != NULL)

{

printf("%s/n", pszErr);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: