Linux C++动态链接库so编写


Linux下的动态链接库是.so文件,即:Shared Object,下面是一个简单的例子说明如何写.so以及程序如何动态载入.so中的函数和对象。

  1. //testso.h:   
  2. #ifndef _TESTSO_H   
  3. #define _TESTSO_H   
  4. extern "C"   
  5. {  
  6.     int myadd(int a, int b);  
  7.     typedef int myadd_t(intint); // myadd function type   
  8. }  
  9. #endif // _TESTSO_H   
  10.   
  11.   
  12. //testso.cpp:   
  13. #include "testso.h"   
  14.   
  15. extern "C"  
  16. int myadd(int a, int  b)  
  17. {  
  18.     return a + b;  
  19. }  

编译so:
g++  -shared  -fPIC  -o testso.so testso.cpp
注意,-shared参数和-fPIC参数非常重要:
-shared 告诉gcc要生成的是动态链接库;
-fPIC 告诉gcc生成的生成的代码是非位置依赖的,方面的用于动态链接。

在主程序里调用这个动态链接库:

  1. //main.cpp:   
  2. #include <stdio.h>   
  3. #include <dlfcn.h>   
  4. // for dynamic library函数   
  5. #include "testso.h"   
  6.   
  7. void print_usage(void)  
  8. {  
  9.     printf("Usage: main SO_PATH/n");  
  10. }  
  11.   
  12. int main(int argc, char *argv[])  
  13. {  
  14.     if (2 != argc) {  
  15.         print_usage();  
  16.         exit(0);  
  17.     }  
  18.   
  19.     const char *soname = argv[1];  
  20.   
  21.     void *so_handle = dlopen(soname, RTLD_LAZY); // 载入.so文件   
  22.     if (!so_handle) {  
  23.         fprintf(stderr, "Error: load so `%s' failed./n", soname);  
  24.         exit(-1);  
  25.     }  
  26.   
  27.     dlerror(); // 清空错误信息   
  28.     myadd_t *fn = (myadd_t*)dlsym(so_handle, "myadd"); // 载入函数   
  29.     char *err = dlerror();  
  30.     if (NULL != err) {  
  31.         fprintf(stderr, "%s/n", err);  
  32.         exit(-1);  
  33.     }  
  34.   
  35.     printf("myadd 57 + 3 = %d/n", fn(57, 3)); // 调用函数   
  36.   
  37.     dlclose(so_handle); // 关闭so句柄   
  38.     return 0;  
  39. }  
  • 1
  • 2
  • 下一页

相关内容