样例
hello.c
#include <stdio.h>
int xx = 996;
void test()
{
printf("test called\n");
}
编译so gcc hello.c -fPIC -shared -o libhello.so
hello_test.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv)
{
void *handle = dlopen("./libhello.so", RTLD_LAZY);
if(!handle) {
printf("open failed: %s\n", dlerror());
return 1;
}
void *xx = dlsym(handle, "xx"); //libtest.so 中定义的xx
if(xx) {
printf("xx is %d\n", *(int*)xx);
} else {
printf("load failed: %s\n", dlerror());
}
void *test = dlsym(handle, "test"); //libtest.so 中定义的xx
if(test) {
void (*f_test)() = (void (*)())test;
f_test();
return 1;
} else {
printf("load failed: %s\n", dlerror());
}
dlclose(handle);
return 0;
}
编译.a gcc hello_test.c -ldl -o hello_test.a
执行.a
xx is 666
test called