I'm making a library that will benefit a lot from inlining its functions, but it's rather large and I've decided to compile it to a static library instead of just a precompiled header. In the code that uses the library, how can I make GCC inline the code (paste in the calling code instead of linking and calling it) from the static library (and is this even possible)?
1 Answer
Yes, modern C++ toolchains are able to inline functions even if they are not inline functions (and their definition is not known in the translation unit where the call happens) when building with link-time optimizations enabled. In GCC, you can enable LTO via the -flto option. Basically, the way these typically work is that the compiler, as it compiles your source code, will not only emit object code directly, but also write its internal representation of your code into the object file. When linking, instead of simply linking object code, the compiler will basically rerun the code generation off of this internal representation for the whole program as if it was written in one big source file. This can dramatically increase the time it takes to build your program. But it allows some important optimizations such as inlining to happen even across translation unit boundaries…
Static libraries are just archives of object files, so if you build your library with LTO enabled and link your calling code against it, the compiler will be able to inline functions right into the calling code. Note that, at the end of the day, it's still up to the compiler to decide whether to inline or not, so there are no guarantees that a function will be inlined for sure…
6 Comments
call instructions (embed functions) from precompiled static libraries into calling code..cpp (according to the first given link in my comment). You didn't explain that LTO is retained in static libraries (your answer says nothing about static libraries), so I thought that you didn't read my question carefully and didn't take into accout that my called code is already compiled to a static library. So, you say that static libraries store LTO info? OK, I'll check that...#define FAST inline __attribute__((always_inline)) helps
callinstructions.