Common object cannot find characters in main binary, C ++

I am experimenting with creating some kind of plugin architecture for the program I wrote, and from my first attempt I had a problem. Is it possible to access characters from the main executable file from within a shared object? I thought everything would be fine:

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; } 

Compiled with

 g++ -fPIC -o testexe testexe.cpp -ldl g++ --shared -fPIC -o testlib.so testlib.cpp 

Output:

 attempting to load fail: ./testlib.so: undefined symbol: _Z3foov 

So obviously this is not normal. Therefore, I have two questions: 1) Is there a way to make the characters of a shared object find in the executable file that it downloaded from 2) If not, how do programs that use plugins usually work, which they manage to get code in arbitrary shared objects to run inside your programs?

+7
c ++ dlopen shared-objects
source share
1 answer

Try:

 g++ -fPIC -rdynamic -o testexe testexe.cpp -ldl 

Without -rdynamic (or something equivalent, such as -Wl,--export-dynamic ), characters from the application itself will not be available for dynamic linking.

+16
source share

All Articles