A static inline
function is, in practice, likely (but not certain) to be inlined by some good optimizing compiler (e.g. by GCC when it is given -O2
) at most of its call sites.
It is defined in a header file, because it then could be inlined at most call sites (perhaps all of them). If it was just declared (and simply "exported") the inlining is unlikely to happen (except if you compile and link with link-time optimizations, a.k.a. LTO, also, e.g. compile and link with gcc -flto -O2
, and that increases a lot the build time).
In practice, the compiler needs to know the body of a function to be able to inline it. So a suitable place is to define it in some common header file (otherwise, it could be inlined only in the same translation unit defining it, unless you enable LTO), so that every translation unit would know the body of that inlinable function.
It is declared static
to avoid multiple definitions (at link time) in case the compiler did not inline it (e.g. when you use its address).
In practice, in C99 or C11 code (except with LTO, which I rarely use), I would always put the short functions I want to be inlined as static inline
definitions in common header files.
Be sure to understand how and when the C preprocessor works. Notice that you could in principle (but it would be very bad practice and disgusting style) avoid defining some static inline
function in a common header file and instead copy and paste its identical definition in multiple .c
files.
(However, that might make sense for generated .c
files, e.g. if you design a compiler emitting C code).
FYI LTO is practically implemented by recent GCC compilers by embedding some internal compiler representation (some GIMPLE) inside object files, and redoing some "compilation" step - using the lto1
frontend - at "link" time. In practice, the entire program is almost compiled "twice".
(actually, I always wondered why the C standardization committee did not decide instead that all explicitly inline
functions are static)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…