用户名:
密 码: 记住
您当前的位置:首页 > 站长百科 > 服务器技术

Linux系统共享库编程

时间:2015-01-23  来源:西部数据  作者:西部数据

一、说明

类似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); 
来顶一下
返回首页
返回首页
推荐资讯
WiFi太不安全:7岁女孩11分钟内入侵公共网络 WiFi太不安全:7岁女孩11分钟内入侵近期刚刚发布研究说WiFi网络能获得人们手机里多少私人信息,
不服跑个分?人工智能也出现“刷分”乱象 不服跑个分?人工智能也出现“刷分2014年,人工智能领域突然爆发,成为了科研和科技创业的热门
相关文章
栏目更新
栏目热门