当前位置:首页 > linux教程 > 列表

Linux系统共享库编程

发布:smiling 来源: PHP粉丝网  添加日期:2014-03-06 22:19:07 浏览: 评论:0 

一、说明

类似Windows系统中的动态链接库,Linux中也有相应的共享库用以支持代码的复用。Windows中为*.dll,而Linux中为*.so。下面详细介绍如何创建、使用Linux的共享库。

二、创建共享库

在mytestso.c文件中,代码如下:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. int GetMax(int a, int b) 
  4. { 
  5. if (a >= b) 
  6. return a;  
  7. return b; 
  8. } 
  9. int GetInt(char* psztxt) 
  10. { 
  11. if (0 == psztxt) 
  12. return -1; 
  13.  
  14. return atoi(psztxt); 
  15. } 

然后使用下列命令进行编译:

gcc -fpic -shared mytestso.c -o mytestso.so 

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

编译成功后,当前目录下有mytestso.so,此时已成功创建共享库mytestso.so。

三、使用共享库

共享库中的函数可被主程序加载并执行,但是不必编译时链接到主程序的目标文件中。主程序使用共享库中的函数时,需要事先知道所包含的函数的名称(字符串),然后根据其名称获得该函数的起始地址(函数指针),然后即可使用该函数指针使用该函数。

在mytest.c文件中,代码如下:

  1. #include <dlfcn.h> 
  2. #include <stdio.h> 
  3. int main(int argc, char* argv[]) 
  4. { 
  5. void* pdlhandle; 
  6. char* pszerror; 
  7.  
  8. int (*GetMax)(int a, int b); 
  9. int (*GetInt)(char* psztxt); 
  10.  
  11. int a, b; 
  12. char* psztxt = "1024"; 
  13.  
  14. // open mytestso.so 
  15. pdlhandle = dlopen("./mytestso.so", RTLD_LAZY); 
  16. pszerror = dlerror(); 
  17. if (0 != pszerror) { 
  18. printf("%sn", pszerror); 
  19. exit(1); 
  20. } 
  21.  
  22. // get GetMax func 
  23. GetMax = dlsym(pdlhandle, "GetMax"); 
  24. pszerror = dlerror(); 
  25. if (0 != pszerror) { 
  26. printf("%sn", pszerror); 
  27. exit(1); 
  28. } 
  29.  
  30. // get GetInt func 
  31. GetInt = dlsym(pdlhandle, "GetInt"); 
  32. pszerror = dlerror(); 
  33. if (0 != pszerror) { 
  34. printf("%sn", pszerror); 
  35. exit(1); 
  36. } 
  37.  
  38. // call fun 
  39. a = 200; 
  40. b = 600; 
  41. printf("max=%dn", GetMax(a, b)); 
  42. printf("txt=%dn", GetInt(psztxt)); 
  43.  
  44. // close mytestso.so 
  45. dlclose(pdlhandle); 
  46. } 

Tags: Linux系统 共享库

分享到: