main.c
#include <dlfcn.h>
#include <stdio.h>
#include "plugin.h"
int main()
{
void *dlp = dlopen("./a.so", RTLD_LAZY);
if(!dlp)
{
printf("dlp Is NULL\n");
return 0;
}
aFunc ap = (aFunc)dlsym( dlp,"a");
printf("ap is [%u] dlerror[%s]\n",ap,dlerror());
if( ap)
{
(*ap)();
}
printf(" normal end\n");
return 0;
}
plugin.h
void a();
typedef void (*aFunc)();
a.c
#include "plugin.h"
void a()
{
c();
}
执行 ./a.out时输出结果
user00@devnet_191_79_sles10_64~/learn/so_test$./a.out
ap is [3591325244] dlerror[(null)]
./a.out: symbol lookup error: ./a.so: undefined symbol: c
如果修改RTLD_NOW则可以检测出未定义符号错误。
dlp Is NULL dlerror[./a.so: undefined symbol: c]
反向引用
gcc -Wl,-export-dynamic main.c -ldl
main.c中包含 函数c的定义
int main()
{
void *dlp = dlopen("./a.so", RTLD_NOW);
if(!dlp)
{
printf("dlp Is NULL dlerror[%s]\n",dlerror());
return 0;
}
aFunc ap = (aFunc)dlsym( dlp,"a");
printf("ap is [%u] dlerror[%s]\n",ap,dlerror());
if( ap)
{
(*ap)();
}
printf(" normal end\n");
return 0;
}
void c()
{
printf("c called\n");
}
最终输出
ap is [4204455484] dlerror[(null)]
c called
normal end