当前位置:   article > 正文

在Linux上创建和使用动态链接库

在Linux上创建和使用动态链接库

首先,我们创建一个动态链接库。假设我们有一个简单的数学函数库,它包含一个加法函数。

math_functions.h(头文件)

  1. // math_functions.h
  2. #ifndef MATH_FUNCTIONS_H
  3. #define MATH_FUNCTIONS_H
  4. int add(int a, int b);
  5. #endif // MATH_FUNCTIONS_H

math_functions.c(库的实现)

  1. // math_functions.c
  2. #include "math_functions.h"
  3. int add(int a, int b) {
  4. return a + b;
  5. }

 要编译这个库,我们使用gcc并指定-shared-fPIC(Position Independent Code)选项来创建动态链接库。

gcc -shared -o libmath_functions.so -fPIC math_functions.c

接下来,我们创建一个使用这个库的主程序。

  1. // main.c
  2. #include <stdio.h>
  3. #include <dlfcn.h>
  4. #include "math_functions.h"
  5. int main() {
  6. void *handle;
  7. int (*add_func)(int, int);
  8. char *error;
  9. // 打开动态链接库
  10. handle = dlopen("./libmath_functions.so", RTLD_LAZY);
  11. if (!handle) {
  12. fprintf(stderr, "%s\n", dlerror());
  13. return 1;
  14. }
  15. // 查找函数地址
  16. dlerror(); /* 清除现有的错误 */
  17. *(void **) (&add_func) = dlsym(handle, "add");
  18. if ((error = dlerror()) != NULL) {
  19. fprintf(stderr, "%s\n", error);
  20. return 1;
  21. }
  22. // 使用函数
  23. int sum = add_func(2, 3);
  24. printf("Sum is: %d\n", sum);
  25. // 关闭动态链接库
  26. dlclose(handle);
  27. return 0;
  28. }

在编译主程序时,我们不需要链接到libmath_functions.so,因为我们在运行时动态加载它。但是,我们需要链接到libdl库,它包含了动态链接所需的函数。

编译主程序

gcc -o main main.c -ldl

现在,你可以运行main程序,它将动态加载libmath_functions.so库,并调用其中的add函数。

运行主程序

./main

输出应该是:

Sum is: 5

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/322549?site
推荐阅读
相关标签
  

闽ICP备14008679号