#include
#include
#include
using namespace std;
int main()
{
// create library
system ( "/usr/bin/gcc -fPIC -shared test.cpp -o libtest.so" );
// load library
void* fLib = dlopen ( "./libtest.so", RTLD_LAZY );
if ( !fLib ) {
cerr << "Cannot open library: " << dlerror() << '\n';
}
if ( fLib ) {
void ( *fn ) () = reinterpret_cast(dlsym(fLib, "test"));
if ( fn ) {
fn();
}
dlclose ( fLib );
}
return 0;
}
它应该被编译”测试.cpp“变成一个动态的图书馆
libtest.so
test
函数并调用此函数,但看起来
dlsym
找不到函数,即使它在那里。
这是
test.cpp
文件:
#include
void test()
{
std::cout << "TEST" << std::endl;
}
这个
main.cpp
编译时使用
g++ -ldl main.cpp -o main
当我执行它时,什么也没有发生:库被加载,但是
fn
libtest.so
.
如果我看看
libtest.so
具有
nm -gD
,我看到了测试函数:
nm -gD libtest.so
U __cxa_atexit@@GLIBC_2.2.5
w __cxa_finalize@@GLIBC_2.2.5
w __gmon_start__
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
0000000000001139 T _Z4testv
U _ZNSolsEPFRSoS_E
U _ZNSt8ios_base4InitC1Ev
U _ZNSt8ios_base4InitD1Ev
U _ZSt4cout
U _ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
U _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
和
c++filt _Z4testv
test()
为什么不呢
找到
test()
? 我怎样才能找到测试函数?