How can I benefit from LTO in my library without requiring it of applications?

1k views Asked by At

I'm developing a library with lots of object files with functions that call each other. I'd like for these functions to benefit from the cross-object-file optimizations enabled by LTO, but without requiring applications that use my library to themselves link with LTO.

Is such a thing possible?

I have already moved some function definitions to headers where practical. A unity build would be problematic because of heavy use of anonymous namespaces and file scope statics.

Once again, my goal is for LTO to occur at library creation time. Not when applications link my library.

I'm on Linux with GCC, but clang is available to me.

2

There are 2 answers

2
ahcox On

To benefit from the same optimisations as LTO of a static library would theoretically enable, give your library a unity build option. This uses one source file which includes all other code in the library into a single translation unit where it is subject to the same whole-library inter-procedural analysis that you are looking for. SQLite is an example of a widely used library using this approach, even distributing itself as a single source file which is the result of all these transitive inclusions pre-processed into the SQLite Amalgamation. Modern CMake supports unity builds.

0
ahcox On

The gcc option -flinker-output=rel[1] might give you something like what you want. You'd use it to run the linker on your library, doing all the LTO stuff in the scope of your library, and then spit out an object file. To turn this back into a static library you could run ar on it [2]. I haven't done this myself though and I think the unity build is the better option.

  1. https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html
  2. https://www.howtogeek.com/427086/how-to-use-linuxs-ar-command-to-create-static-libraries/