国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Linux > 正文

Linux系統共享庫編程

2024-08-27 23:57:43
字體:
來源:轉載
供稿:網友

一、說明

類似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); 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 思南县| 宁强县| 涪陵区| 象山县| 台州市| 柳河县| 宣城市| 西青区| 百色市| 札达县| 西盟| 西昌市| 利辛县| 疏勒县| 高平市| 临沂市| 顺昌县| 连平县| 邵武市| 宁阳县| 谷城县| 灌南县| 故城县| 宿迁市| 当阳市| 庐江县| 河北区| 兴海县| 克什克腾旗| 陕西省| 本溪市| 渝中区| 凤山市| 永新县| 安义县| 绿春县| 鹿邑县| 玉龙| 达尔| 汝州市| 革吉县|