当 C++ 没有稳定的 ABI 时,为什么可以链接到 C++ 动态库?

agr*_*l-d 4 c++ boost ffi abi

以 Boost 为例,boost::filesystem当 C++ 没有稳定的 ABI 时,为什么我能够从我的 C++ 程序进行链接。

我的系统中安装了 Boost,并且玩具程序能够使用 进行链接-lboost_filesystem,即使boost::filesystem公开了 C++ API(没有 extern 'C' )。

那么,是否可以创建可以被各种编译器版本链接的C++共享库呢?Boost 如何在没有“extern C”的情况下实现这一目标?

我试过:

#include <iostream>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int main() {
    // Replace "/path/to/directory" with the path to the directory you want to list
    std::string directory_path = "/path/to/directory";

    try {
        // Check if the given path exists and is a directory
        if (fs::exists(directory_path) && fs::is_directory(directory_path)) {
            std::cout << "Listing files in directory: " << directory_path << std::endl;

            // Iterate through the files in the directory
            for (const auto& entry : fs::directory_iterator(directory_path)) {
                std::cout << entry.path() << std::endl;
            }
        } else {
            std::cerr << "Error: Invalid directory path." << std::endl;
            return 1;
        }
    } catch (const fs::filesystem_error& ex) {
        std::cerr << "Error: " << ex.what() << std::endl;
        return 1;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

g++ -o fs fs.cpp -I/usr/include/boost -I/usr/include/boost/filesystem -I/usr/include/boost/system -lboost_system -lboost_filesystem -std=c++14

预期:应该出现链接错误,因为 C++ 没有稳定的 ABI

得到:编译成功。

sel*_*bie 6

我不确定 ABI 本身,但将一个编译器构建的 C++ 库与另一个编译器编译的程序链接起来的真正关键在于两个编译器共享相同的名称重整模式。

事实上,g++ 和 clang++ 的工作原理相同,并且多年来一直具有相同的架构。

但正如这个问题和答案所揭示的那样,尝试通过使用 MinGW 在 Windows 上编译库并期望它与 Visual Studio 链接来执行类似的操作是行不通的。除非近年来发生一些变化,否则可能不可能。

  • Clang 是一个变色龙 - 如果您使用 Windows 版本的 clang++,它与 Visual Studio 匹配。 (2认同)