Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use lto with static libraries?

Tags:

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.

like image 385
Tavian Barnes Avatar asked Sep 16 '14 21:09

Tavian Barnes


People also ask

How do static libraries work?

In computer science, a static library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, producing an object file and a stand-alone executable.

What is a static library How does it work how do you create one and how do you use it?

A static library which is a statically linked library is a set of routines, external functions and variables that are resolved in a caller called compile-time and copied into a target application by a compiler. Any static library function can call a function or procedure in another static library.

What is static library GCC?

A static library is basically a set of object files that were copied into a single file. This single file is the static library. The static file is created with the archiver (ar). First, calc_mean.c is turned into an object file: gcc -c calc_mean.c -o calc_mean.o.


1 Answers

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 
like image 139
Tavian Barnes Avatar answered Sep 24 '22 18:09

Tavian Barnes