c++ - 加载 .so 库 C++

标签 c++ shared-libraries

我正在尝试加载库 library.so,当我尝试 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; }

最佳答案

dlopen 在它可以搜索的路径上非常受限(为了保持简短:默认路径加上 LD_LIBRARY_PATH 变量——请参阅完整的 documentation 以获得完整的信息列表)。您的 ifstream 查找当前目录(无论它是什么),默认情况下它很可能不包含在 dlopen 考虑的路径中。

解决方案包括:

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

关于c++ - 加载 .so 库 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16335671/

相关文章:

c++ - 使用 -std=c++0x 导致错误 : ‘Iterator’ does not name a type error

php - 想要使用底层 C++ 构建基于浏览器的 Web 应用程序,我在看 AJAX、LAMP 吗?

c++ - 从CMake中的lib目录加载共享库?

linux - Linux 库的软件包是什么?

c - 声明 -nostartfiles 时 pthread_atfork 无法编译

c++ - 如何确定通过套接字接收到的(序列化和模板化)对象是什么类型?

c++ - 注入(inject)的 DLL 中的异常是否会导致整个程序崩溃?

c++ - 56:68:错误:预期表达

c++ - 如何在 bleeding edge linux 上编译程序以在旧 linux 上运行

python - 如何在 Ubuntu 下用 Python 编译和包含 Matlab 文件