1.创建动态链接库hello.so:
#include <stdio.h>
void hello(void)
{
printf("Hello, this is hello.so\n");
}$gcc -fpic -shared -o hello.so hello_so.c2.使用动态链接库hello.so:
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char *argv[])
{
void *handle;
void (*hello)(void);
char *error;
handle = dlopen("./hello.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror(); /* Clear any existing error */
/* check the man page for the reason */
*(void **) (&hello) = dlsym(handle, "hello");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
(*hello)();
dlclose(handle);
return 0;
}$gcc -rdynamic -o dl_test dl_test.c -ldl
本文介绍如何使用GCC编译器创建一个简单的动态链接库(.so文件),并演示了如何在C程序中加载和调用该动态链接库中的函数。通过dlfcn.h中的函数实现动态链接。
1104

被折叠的 条评论
为什么被折叠?



