我正在尝试为我编写的程序创建一种插件架构,而在我的首次尝试中遇到了问题。是否可以从共享对象中访问主可执行文件中的符号?我认为以下代码是可以的:
testlib.cpp:
testlib.cpp:
void foo();
void bar() __attribute__((constructor));
void bar(){ foo(); }
testexe.cpp:
#include <iostream>
#include <dlfcn.h>
using namespace std;
void foo()
{
cout << "dynamic library loaded" << endl;
}
int main()
{
cout << "attempting to load" << endl;
void* ret = dlopen("./testlib.so", RTLD_LAZY);
if(ret == NULL)
cout << "fail: " << dlerror() << endl;
else
cout << "success" << endl;
return 0;
}
编译环境:
g++ -fPIC -o testexe testexe.cpp -ldl
g++ --shared -fPIC -o testlib.so testlib.cpp
输出:
attempting to load
fail: ./testlib.so: undefined symbol: _Z3foov
显然,这是不行的。所以我有两个问题: 1)有没有办法使共享对象在加载自身的可执行文件时找到符号。 2)如果没有,那么使用插件的程序通常如何工作,以便能够在其程序内运行任意共享对象中的代码?
-fPIC
呢?它创建的是可执行文件,而不是共享库。我认为-fPIC
是多余的。 - Rick