网站地图    收藏   

主页 > 系统 > 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. if (a >= b) 
  5. return a;  
  6. return b; 
  7. int GetInt(char* psztxt) 
  8. if (0 == psztxt) 
  9. return -1; 
  10.  
  11. return atoi(psztxt); 

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

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. void* pdlhandle; 
  5. char* pszerror; 
  6.  
  7. int (*GetMax)(int a, int b); 
  8. int (*GetInt)(char* psztxt); 
  9.  
  10. int a, b; 
  11. char* psztxt = "1024"
  12.  
  13. // open mytestso.so 
  14. pdlhandle = dlopen("./mytestso.so", RTLD_LAZY); 
  15. pszerror = dlerror(); 
  16. if (0 != pszerror) { 
  17. printf("%sn", pszerror); 
  18. exit(1); 
  19.  
  20. // get GetMax func 
  21. GetMax = dlsym(pdlhandle, "GetMax"); 
  22. pszerror = dlerror(); 
  23. if (0 != pszerror) { 
  24. printf("%sn", pszerror); 
  25. exit(1); 
  26.  
  27. // get GetInt func 
  28. GetInt = dlsym(pdlhandle, "GetInt"); 
  29. pszerror = dlerror(); 
  30. if (0 != pszerror) { 
  31. printf("%sn", pszerror); 
  32. exit(1); 
  33.  
  34. // call fun 
  35. a = 200; 
  36. b = 600; 
  37. printf("max=%dn", GetMax(a, b)); 
  38. printf("txt=%dn", GetInt(psztxt)); 
  39.  
  40. // close mytestso.so 
  41. dlclose(pdlhandle); 

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

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

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

添加评论