C++ 加载.so库C++;

C++ 加载.so库C++;,c++,shared-libraries,C++,Shared Libraries,我正在尝试加载库。所以,当我尝试if exist时返回true,但当我使用dlopen时返回库不存在 std::ifstream ifile("library.so"); if (ifile) { cout << "Exist!" << std::endl; } cout << "C++ dlopen demo\n\n"; // open the library cout << "Opening hello.so...\n"; void

我正在尝试加载库。所以,当我尝试if exist时返回true,但当我使用dlopen时返回库不存在

std::ifstream ifile("library.so"); if (ifile) {
    cout << "Exist!" << std::endl; }

cout << "C++ dlopen demo\n\n";

// open the library cout << "Opening hello.so...\n"; void* handle = dlopen("library.so", RTLD_LAZY);

if (!handle) {
    cerr << "Cannot open library: " << dlerror() << '\n';
    return 1; }
std::ifstream ifile(“library.so”);如果(ifile){

cout
dlopen
在它可以搜索的路径上受到很大限制(为了保持简短:默认路径加上
LD\u LIBRARY\u PATH
变量——请参阅完整列表)。您的
ifstream
在当前目录中查找(无论它是什么),在默认情况下,
dlopen
考虑的路径中很可能不包括它

解决方案包括:

  • 相应地设置LD_LIBRARY_PATH(这通常是首选方法)
  • 使用绝对路径而不是相对路径
  • 将库放入默认路径之一(例如
    /lib
    /usr/lib

可能是ifstream对象锁定了file对象,请在使用dlopen之前尝试执行
ifile.close()