如何将lto与静态库一起使用?

时间:2021-11-10 13:40:46

When I try to build static libraries with -flto, I get undefined reference errors:

当我尝试使用-flto构建静态库时,我得到未定义的引用错误:

library.cpp:

library.cpp:

#include <iostream>

void foo() {
  std::cout << "Test!" << std::endl;
}

main.cpp:

main.cpp中:

void foo();

int main() {
  foo();
  return 0;
}

Compilation output:

编译输出:

$ g++ -flto -c library.cpp
$ ar rcs library.a library.o
$ g++ -flto main.cpp library.a
/tmp/ccZIgxCY.ltrans0.ltrans.o: In function `main':
ccZIgxCY.ltrans0.o:(.text+0x5): undefined reference to `foo()'
collect2: error: ld returned 1 exit status

It works fine if I link with library.o instead of library.a. What am I missing? This is with GCC 4.9.1 and binutils 2.24.

如果我链接library.o而不是library.a,它工作正常。我错过了什么?这与GCC 4.9.1和binutils 2.24有关。

1 个解决方案

#1


19  

The answer, as I found out from this post by GCC developer Honza Hubička, is to use the gcc-ar wrapper instead of ar by itself:

正如我在GCC开发人员HonzaHubička的这篇文章中发现的那样,答案是使用gcc-ar包装器而不是ar本身:

$ gcc-ar rcs library.a library.o

This invokes ar with the right plugin arguments, in my case were

这会使用正确的插件参数调用ar,在我的例子中是

--plugin /usr/lib/gcc/x86_64-unknown-linux-gnu/4.9.1/liblto_plugin.so

#1


19  

The answer, as I found out from this post by GCC developer Honza Hubička, is to use the gcc-ar wrapper instead of ar by itself:

正如我在GCC开发人员HonzaHubička的这篇文章中发现的那样,答案是使用gcc-ar包装器而不是ar本身:

$ gcc-ar rcs library.a library.o

This invokes ar with the right plugin arguments, in my case were

这会使用正确的插件参数调用ar,在我的例子中是

--plugin /usr/lib/gcc/x86_64-unknown-linux-gnu/4.9.1/liblto_plugin.so