c++ - 在运行时读取 libstdc++ 版本

标签 c++ libstdc++

我的申请受到 a bug 的影响在旧版本的 libstdc++ 中以相当严重的数据丢失方式。如何使用 -rpathLD_LIBRARY_PATH 选择正确的库版本的补救措施是已知的,但对于部署和构建中的更改并不可靠。在我自己被咬了不止一次之后,我想停止痛苦并引入运行时检查以获取足够新的 libstdc++ 版本。如果部署未能使用正确的版本,我如何访问该版本以打印一条大警告消息。请注意,我需要 gcc 8 附带的 次要 版本 libstdc++.so.6.0.25 a.k.a. GLIBCXX_3.4.25

最佳答案

这是一个 linux 程序,它简单地列出了它拥有的 DSO 的绝对真实路径 加载(由 dl_iterate_phdr 枚举)是可访问的文件。 (所有 linux 程序加载 linux-vdso.so ,它实际上不是一个文件)。

main.cpp

#include <link.h>
#include <climits>
#include <cstdlib>
#include <string>
#include <vector>
#include <iostream>

int
get_next_SO_path(dl_phdr_info *info, size_t, void *p_SO_list)
{
    auto & SO_list =
        *static_cast<std::vector<std::string> *>(p_SO_list);
    auto p_SO_path = realpath(info->dlpi_name,NULL);
    if (p_SO_path) {
        SO_list.emplace_back(p_SO_path);
        free(p_SO_path);
    }
    return 0;
}

std::vector<std::string>
get_SO_realpaths()
{
    std::vector<std::string> SO_paths;
    dl_iterate_phdr(get_next_SO_path, &SO_paths);
    return SO_paths;
}


int main()
{
    auto SO_paths = get_SO_realpaths();
    for (auto const & SO_path : SO_paths) {
        std::cout << SO_path << std::endl;
    }
    return 0;
}

这对我来说是这样的:

$ g++ -Wall -Wextra main.cpp && ./a.out
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25
/lib/x86_64-linux-gnu/libgcc_s.so.1
/lib/x86_64-linux-gnu/libc-2.27.so
/lib/x86_64-linux-gnu/libm-2.27.so
/lib/x86_64-linux-gnu/ld-2.27.so

Live demo

如您所见,出现了完整版本。通过一些文件名解析,你 可以从那里拿走。根据 get_SO_realpaths 获取整个 DSO 列表, 在寻找任何 libstdc++ 之前,如果需要,您可以检测到异常的可能性 正在加载多个 libstdc++

关于c++ - 在运行时读取 libstdc++ 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52974593/

相关文章:

c++ - 64 位系统可以运行包含一些内联汇编的 32 位软件吗?

c++ - 通过qt中的打印机设备打印pdf文件

c++ - 如何使用 stdlibc++ 为 OS X 64b 平台编译 boost?

c++ - '_Unwind_GetIPInfo' 符号

c++ - 为什么将对象引用参数传递给线程函数无法编译?

c++ - 使用反引号时程序不输出

c++ - 抽象接口(interface)继承

c++ - 我如何将 Octave (matlab 克隆)与 qt creator 集成

C++ 11 正则表达式错误

glibc - 为什么相同的二进制文件需要在一台 64 位 RHEL 5.4 服务器上使用 linux-vdso.so.1,而不是在另一台服务器上?