[关闭]
@breakerthb 2017-05-08T06:54:01.000000Z 字数 1519 阅读 1235

Linux动态库

Linux


1. 创建动态库文件

  1. // getmaxlen.h
  2. #ifndef _GETMAXLEN_H_
  3. #define _GETMAXLEN_H_
  4. int getMax(int a, int b);
  5. #endif
  1. // getmaxlen.c
  2. #include "getmaxlen.h"
  3. int getMax(int a, int b)
  4. {
  5. if (a > b)
  6. {
  7. return a;
  8. }
  9. else
  10. {
  11. return b;
  12. }
  13. }

2. 编译和使用动态库

2.1 编译

gcc getmaxlen.c -fPIC -shared -o libmax.so

由以上命令生成动态库libmax.so,为了不需要动态加载动态库,在命令时需以lib开头以.so为后缀。

A
-fPIC 表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的
-shared 指明编译成动态库

2.2 调用

  1. // test.c
  2. #include <stdio.h>
  3. #include "getmaxlen.h"
  4. int main()
  5. {
  6. int a = 5;
  7. int b = 3;
  8. printf("The max is %d\n", getMax(a, b));
  9. return 0;
  10. }
  1. gcc test.c -L. -lmax -o test
A
-L 指明动态库所在的目录
-l 指明动态库的名称,该名称是处在头lib 和后缀.so 中的名称,如上动态库libtest.so的l参数为-lmax。

2.3 测试

ldd test

ldd 测试可执行文件所使用的动态库

2.4 运行

./test

结果如下:

The max is 5

3. 规定so路径

一般情况下,调用程序和so文件需要在同一个目录下,这样才能保证动态链接时能够找到。如果不在同一个目录,需要通过配置LD_LIBRARY_PATH环境变量指定寻找路径。

比如:

gcc getmaxlen.c -fPIC -shared -o lib/libmax.so
gcc test.c -Llib -lmax -o test

执行一下:

./test

可以看到如下结果:

如果需要它不在同一个目录执行,有另一个方法:

gcc getmaxlen.c -fPIC -shared -o lib/libmax.so
gcc test.c -Llib -lmax -Wl,-rpath=lib -o test

-Wl,-rpath=为程序指定链接库的位置。

4. 动态加载方式使用动态库

  1. //动态库的动态加载使用
  2. #include <stdio.h>
  3. #include <dlfcn.h>
  4. int main()
  5. {
  6. void *handle = NULL;
  7. int (*getMax)(int a, int b);
  8. handle = dlopen("./libmax.so", RTLD_LAZY);
  9. if(handle == NULL)
  10. {
  11. printf("dll loading error.\n");
  12. return 0;
  13. }
  14. getMax = (int(*)(int,int))dlsym(handle, "getMax");
  15. if (getMax==NULL)
  16. {
  17. printf("%s:dlsym:'%s'\n","getMaxLen",dlerror());
  18. return 0;
  19. }
  20. printf("%d\n",getMax(5, 15));
  21. return 0;
  22. }

编译命令:

gcc test.c -ldl -o test

-ldl:使用动态库相关函数需使用该参数

注意:

另:使用c++时,so文件在声明是要加extern"C",才能正确获取函数地址.否则,在dlsym可能的错误:找不到函数(undefined symbol).

getmaxlen.h 中声明如:

extern "C" int getMaxLen(int *sel,int N);
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注