首先,我们创建一个动态链接库。假设我们有一个简单的数学函数库,它包含一个加法函数。
math_functions.h(头文件)
// math_functions.h
#ifndef MATH_FUNCTIONS_H
#define MATH_FUNCTIONS_H
int add(int a, int b);
#endif // MATH_FUNCTIONS_H
math_functions.c(库的实现)
// math_functions.c
#include "math_functions.h"
int add(int a, int b) {
return a + b;
}
要编译这个库,我们使用gcc并指定-shared
和-fPIC
(Position Independent Code)选项来创建动态链接库。
gcc -shared -o libmath_functions.so -fPIC math_functions.c
接下来,我们创建一个使用这个库的主程序。
// main.c
#include <stdio.h>
#include <dlfcn.h>
#include "math_functions.h"
int main() {
void *handle;
int (*add_func)(int, int);
char *error;
// 打开动态链接库
handle = dlopen("./libmath_functions.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
return 1;
}
// 查找函数地址
dlerror(); /* 清除现有的错误 */
*(void **) (&add_func) = dlsym(handle, "add");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
return 1;
}
// 使用函数
int sum = add_func(2, 3);
printf("Sum is: %d\n", sum);
// 关闭动态链接库
dlclose(handle);
return 0;
}
在编译主程序时,我们不需要链接到libmath_functions.so
,因为我们在运行时动态加载它。但是,我们需要链接到libdl
库,它包含了动态链接所需的函数。
编译主程序
gcc -o main main.c -ldl
现在,你可以运行main
程序,它将动态加载libmath_functions.so
库,并调用其中的add
函数。
运行主程序
./main
输出应该是:
Sum is: 5