loading .so library C++

2019-08-10 03:11发布

问题:

I'm trying load library library.so, when i try if exist return true, but when I use dlopen return library doesn't exist.

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

回答1:

dlopen is quite restricted in the paths it can search (to keep it short: the default paths plus LD_LIBRARY_PATH variable -- see the full documentation for a complete list). Your ifstream looks in the current directory (whatever it is), which is quite probably not included by default in the paths that dlopen considers.

Solutions include:

  • Setting LD_LIBRARY_PATH accordingly (which is usually the preferred method).
  • Using an absolute path instead of a relative one.
  • Putting your library in one of the default paths (eg. /lib or /usr/lib).