Linux C编程(6) 使用动态库
来源:互联网 发布:mac 关闭手写输入 编辑:程序博客网 时间:2024/05/16 08:23
生成动态库
文件名:TestSO.c
#include "testso.h"#include <stdio.h>#include <stdlib.h>void test_a(){ printf("this is in test_a...\n");}void test_b(){ printf("this is in test_b...\n");}void test_c(){ printf("this is in test_c...\n");}
编译成动态库命令
gcc testso.c -fPIC -shared -o libtestso.so
动态库隐式链接
当动态库的位置或者名字发生改变时,程序将无法运行。
复制libtestso.so到/usr/lib目录下。要有root权限才能复制到系统目录中。
文件名:main.c
#include "testso.h"int main(){ test_a(); test_b(); test_c(); return 0;}
生成可执行程序,名为test。
gcc main.c -o test -ltestso -L/usr/lib
使用ldd测试链接是否成功,即是否链接上了动态库:
ldd test
linux-gate.so.1 => (0xb778c000)
libtestso.so => /usr/lib/libtestso.so (0xb7776000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb75cc000)
/lib/ld-linux.so.2 (0xb778d000)
运行结果如下:
this is in test_a...
this is in test_b...
this is in test_c...
注意,如果依赖的动态库(libtestso.so)还依赖其他的动态库,则编译系统会调用动态连接器连接所依赖的动态库。所以,要保证动态连接器能找到依赖的动态库(libtestso.so依赖的库,如果有的话),否者编译会出错。
动态库显示链接
文件名:dlltest.c
#include "testso.h"#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <dlfcn.h>#include <sys/types.h> int main(){void * pHandle;void (*pFunc)();
//RTLD_NOW:将共享库中的所有函数加载到内存<p align="left">//RTLD_LAZY:会推后共享库中的函数的加载操作,直到调用dlsym()时方加载某函数pHandle = dlopen("./libtestso.so", RTLD_NOW);if(!pHandle){printf("Can't find libtestso.so\n");return -1;}else{printf("find libtestso.so\n");} void (*pTest1)() = dlsym(pHandle, "test_a");if(pTest1){(*pTest1)();}else{printf("load test_a function is error\n");} return 0;}</p>
生成可执行程序,名为dlltest。
gcc dlltest.c -o dlltest -ldl
编译时要使用系统的共享库dl。其中有dlopen、dlsynm等函数。
运行结果如下:
find libtestso.so
this is in test_a...
- Linux C编程(6) 使用动态库
- linux C++/C 动态链接库使用
- linux C++/C 动态链接库使用
- linux下Eclipse进行C编程时动态链接库的生成和使用
- Linux C编程(7) 使用相对路径加载动态库-LD_LIBRARY_PATH
- Linux C编程(8) 使用相对路径加载动态库-rpath和$ORIGIN
- linux c动态链接库的使用
- linux c动态链接库的使用
- 【ARM-Linux开发】linux下Eclipse进行C编程时动态链接库的生成和使用
- linux下Eclipse进行C编程时动态链接库
- linux下编程动态库和静态库编译使用
- Linux C 静态库和动态库的使用
- c语言起步(2):Linux动态链接库的使用
- linux 动态库使用
- Linux 动态库使用
- Linux下动态链接库的创建和使用及C调用matlab动态库问题
- Linux下动态链接库的创建和使用及C调用matlab动态库问题
- Linux C语言开发 动态链接库以及静态链接库编程简单介绍
- 毛泽东:论持久战
- 停止事件冒泡的方法
- ssh免输入及多tab clone的脚本
- kdj,rsi,macd 指标解释
- Jasper Report v1.0用户手册中文版
- Linux C编程(6) 使用动态库
- python获取上级目录
- 活动选择问题
- 如何将中缀式转化成前缀式和后缀式
- 读<<软件工程的思想>>有感
- c++primer学习笔记2 - 标准库类型
- jasper在JSP中导出pdf和xls
- 数字三角形问题
- android touch事件传递