1.创建动态链接库hello.so:
#include <stdio.h>
void hello(void)
{
printf("Hello, this is hello.so\n");
}
$gcc -fpic -shared -o hello.so hello_so.c
2.使用动态链接库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