网站地图    收藏   

主页 > 系统 > linux系统 >

Linux系统共享库编程 - linux教程

来源:自学PHP网    时间:2014-11-28 23:06 作者: 阅读:次

[导读] 一、说明类似Windows系统中的动态链接库,Linux中也有相应的共享库用以支持代码的复用。Windows中为* dll,而Linux中为* so。下面详细介绍...

Linux系统共享库编程

一、说明

类似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. } 

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论