#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
if ((fp = fopen("hello.c", "w")) == NULL) {
fprintf(stderr, "file cannot open");
exit(EXIT_FAILURE);
}
fprintf(fp,
"#include <stdio.h>\n"
"void hello(void) { printf(\"hello dl world!\\n\"); }\n"
);
fclose(fp);
system("gcc -shared hello.c -o hello.so");
void *dl = dlopen("./hello.so", RTLD_LAZY);
if (dl == NULL) {
fprintf(stderr, "dl cannot open");
exit(EXIT_FAILURE);
}
void (*f)(void) = dlsym(dl, "hello");
if (f == NULL) {
fprintf(stderr, "dl cannot open");
exit(EXIT_FAILURE);
}
f();
dlclose(dl);
return 0;
}