linux 下创建动态链接库的一个很简单的例子

来源:互联网 发布:网络启动设置方法 编辑:程序博客网 时间:2024/06/05 07:15
在目录 /usr/local/src/so_lib_test 下面创建三个文件: libtest.h, libtest.c, test_main.c
libtest.h 的内容为:
[cpp] view plaincopyprint?
  1. /* 这里只声明了一个函数 */  
  2. int Add(intint);  
libtest.c 的内容为:
[cpp] view plaincopyprint?
  1. #include "libtest.h"  
  2.   
  3. int Add(int a, int b)  
  4. {  
  5.   return ((a)+(b));  
  6.   }  
test_main.c 的内容为:

[cpp] view plaincopyprint?
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <dlfcn.h>  
  4.   
  5. int main(int argc, char **argv)  
  6. {  
  7.    void *handle;  
  8.    int (*lpAdd)(intint);  
  9.    char *error;  
  10.   
  11.    if ( !(handle = dlopen("libtest.so", RTLD_LAZY)) )  
  12.    {  
  13.      fprintf(stderr, "%s\n", dlerror());  
  14.      return 1;  
  15.     }  
  16.    else  
  17.      printf("dlopen() function load libtest.so succeeded!\n");  
  18.   
  19.    dlerror();    /* Clear any existing error */  
  20.    *(void **) (&lpAdd) = dlsym(handle, "Add");  
  21.    if ((error = dlerror()) != NULL)  
  22.    {  
  23.      fprintf(stderr, "%s\n", error);  
  24.      return 1;  
  25.     }  
  26.    else  
  27.      printf("Get functino offset address succeeded!\n");  
  28.   
  29.    printf("Add(3,7) function output is: %d\n", (*lpAdd)(3, 7));  
  30.   
  31.    if (dlclose(handle))  
  32.    {  
  33.      error = dlerror();  
  34.      fprintf(stderr, "%s\n", error);  
  35.      return 1;  
  36.      }  
  37.    else  
  38.      printf("dlclose() function close dynamic link library succeeded!\n");  
  39.   
  40.    return 0;  
  41. }  

执行命令 gcc libtest.c -fPIC -shared -o libtest.so

在当前目录下会生成一个名为 libtest.so 的动态库文件。

执行命令 gcc -o test_main  test_main.c -L. -ltest -ldl
在当前目录下会生成一个名为 test_main 的可执行文件

执行命令 ./test_main
会报出错误提示:
 error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory

这是因为需要告诉操作系统到哪里才能找到 libtest.so 文件,执行命令
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/src/so_lib_test
(除了使用这条命令之外还有其他方法,这里就不介绍了)

再执行命令 ./test_main

可以看到以下输出
dlopen() function load libtest.so succeeded!
Get functino offset address succeeded!
Add(3,7) function output is: 10
dlclose() function close dynamic link library succeeded!

对于 dlopen(), dlsym(), dlclose() 函数的用法,在网页: http://linux.die.net/man/3/dlopen 上有详细介绍
0 0
原创粉丝点击