库操作相关

来源:互联网 发布:淘宝添加视频代码 编辑:程序博客网 时间:2024/06/03 09:26
库操作相关

nm   :列出编入目标文件或二进制文件的所有符号。
ar :操作高度结构化的存档文件。
ranlib :生成存档文件的索引。  == ar -s file
ldd :输出文件所要求的共享库的名字。
ldconfig :ldconfig决定目录/usr/lib和/lib下的共享库所需的运行的链接,这些链接在命令行上的libs指定并保存在/etc/ld.so.conf中。命令ldconfig和动态链接/装载工具ld.so协同工作,一起来创建和维护对最新版本共享库的链接。
ld.so使用两个环境变量:
LD_LIBRARY_PATH  冒号分隔;搜索运行时的共享库目录。
LD_PRELOAD  空格分隔;需要在所有库加载之前加载。

静态库创建及使用:
首先创建库的源文件libx.c
gcc -c libx.c -o libx.o 编译生成目标文件
ar rcs libx.a libx.o 创建库文件
编写调用库的源文件testx.c
gcc testx.c -o testx -static -L . -lx
file testx

动态库创建及使用:
1.编译目标文件时使用GCC的-fPIC选项,这能产生与位置无关的代码并加载到任何位置。
2.使用GCC的-shared和-soname选项。
3.使用GCC的-wl选项把参数传递给连接器ld
4.使用GCC的-l选项显式地链接C库,以保证可以得到所需的启动代码。

gcc -fPIC -g -c libx.c -o libx.o
gcc -g -shared -Wl,-soname,libx.so -o libx.so.1.0.0 libx.o -lc

动态加载的共享对象
dl接口提供了4个函数处理加载,使用,卸载共享对象的所有任务及检查错误。
加载共享对象:
void *dlopen(const char *filename,int flag);
使用共享对象:
void *dlsym(void *handle,char *symbol);
检查错误:
const char *dlerror(void);
卸载共享对象:
int dlclose(void *handle);



#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int main(void)
{
void *handle;
void (*errfcn)(const char *fmt,...);
const char *errmsg;
FILE *pf;
handle = dlopen("./libx.so",RTLD_NOW);
if(handle == NULL)
{
fprintf(stderr,"Failed to load liberr.so: %s\n",dlerror());
exit(EXIT_FAILURE);
}
dlerror();
errfcn = dlsym(handle,"err_ret");
if((errmsg = dlerror()) != NULL)
{
fprintf(stderr,"Didn't find err_ret: %s \n",errmsg);
exit(EXIT_FAILURE);
}
if((pf = fopen("fooba","r")) == NULL)
{
errfcn("Count't open foobar");
}
dlclose(handle);
exit(EXIT_SUCCESS);
}

gcc -g -Wall dltest.c -o dltest -ldl
原创粉丝点击