How can I use lto with static libraries?

回眸只為那壹抹淺笑 提交于 2019-11-27 14:38:35

问题


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

library.cpp:

#include <iostream>

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

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.


回答1:


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-ar rcs library.a library.o

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

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



回答2:


As a complimentary answer: with GCC there is also the possibility to use -ffat-lto-objects which adds classic object code to the files in the archive. This makes it possible to use the static library in code that you build without -flto.



来源:https://stackoverflow.com/questions/25878407/how-can-i-use-lto-with-static-libraries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!