为什么断言在链接阶段失败?

Why an assertion failed during the linking phase?

我想静态 link libdds.a 到一个简单的 C++ 应用程序(进行一些测试)。这是我的 C++ 代码(文件名为 bridge.cpp):

#include <iostream>

int main()
{
    std::cout << "Hello world!" << std::endl;

    return 0;
}

此代码暂时不使用 libdds.a 中的函数,但我想确保编译工作正常。所以我尝试编译:

$ g++ -Wall -o bridge bridge.cpp -L. -ldds
collect2: fatal error: ld terminated with signal 6 [Abandon], core dumped
compilation terminated.
ld: ../../src/lto-plugin/lto-plugin.c :388 : dump_symtab:  assertion « resolution != LDPR_UNKNOWN » failed.

这里是 g++ld 的版本:

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
$ ld --version
GNU ld (GNU Binutils for Ubuntu) 2.26.1

我没有使用任何 IDE 并且我使用完全相同的先前命令从命令行编译。我在 Ubuntu 16.04.6 LTS:

$ lsb_release -a
LSB Version:    core-9.20160110ubuntu0.2-amd64:core-9.20160110ubuntu0.2-noarch:printing-9.20160110ubuntu0.2-amd64:printing-9.20160110ubuntu0.2-noarch:security-9.20160110ubuntu0.2-amd64:security-9.20160110ubuntu0.2-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial

这个错误是什么意思,我该如何更正它?

此错误表示 lto-plugin 无法解析至少一个符号。事实上,静态库 dds.a 是用旧版本的 GCC 编译的。例如,如果您尝试使用 lto1 读取其中的一个目标文件,您将收到此错误:

$ /usr/lib/gcc/x86_64-linux-gnu/5/lto1 Par.o
Reading object files: Par.olto1: fatal error: bytecode stream generated with LTO version 2.1 instead of the expected 4.1

要更正它,您有两种选择:禁用 LTO 或重新编译 dds.a(如评论中所建议)。

要禁用 LTO,您可以使用 -fno-use-linker-plugin GCC 选项,但您会收到另一个错误:

$ g++ -Wall -fno-use-linker-plugin -o bridge bridge.cpp -L. -ldds
/usr/bin/ld : skipping incompatible ./libdds.a when searching for -ldds

事实上,目标文件是 elf32-i386 格式,您尝试 link 它们具有 elf64-x86-64 文件格式:

$ objdump -p Par.o
Par.o:     file format elf32-i386
$ g++ -c bridge.cpp 
$ objdump -p bridge.o 
bridge.o:     file format elf64-x86-64

在这一点上,link dds.a 对您的程序的唯一好的解决方案是使用您将用于编译最终应用程序的同一编译器重新编译它。