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。其中有dlopendlsynm等函数。

   运行结果如下:

   find libtestso.so

   this is in test_a...

 


 

 


0 0