To place an inline
function definition in a C header file for a function that should be inlined into multiple other units, should inline
or static inline
be used? I've been Googling for a little while but there seems to be no concise explanation of the difference so far.
The proper way to inline a function in C is as follows:
inline
function in the headerextern inline
function in the implementation file.example.h
inline int example(int val) {
return (val << 2) | 1;
}
example.c
#include "example.h"
extern inline int example(int val);
Can't you just declare a
static inline
in the header, without .c?
This would result in separate independent function definitions in each translation unit from which the header is included. In addition in increasing the size of compiled code unnecessarily, this would produce some unexpected behavior when you obtain a pointer to your inline functions: rather than producing the same address, the addresses of the inline function taken in different translation units would produce different values.
but if one guards the header file the re-defining can be avoided, can't it?
No, absolutely not. This has nothing to do with multiple inclusions of the same header. Each translation unit is compiled separately from other translation units, so when the compiler sees a static function, it has no choice but to create a private duplicate invisible from the outside of the translation unit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With