I’m re-writing a small C math library of mine that will end up as a static library for the user and would like to benefit from inlining for my vector math interface.
I have the following:
[ mymath.h ]
...
...
extern float clampf( float v, float min, float max );
...
...
[ mymath.c ]
inline float clampf( float v, float min, float max )
{
if( v < min ) v = min;
if( v > max ) v = max;
return v;
}
Since my library will be static and I’m only going to provide the .h (and the .lib) to the user, will the clampf function be inlined in their program when compiled?
Am I doing the right thing but declaring the function extern in the .h and inline in the .c?
You have it almost correct. You actually have it backwards; for inline functions you must put the
inlinedefinition in the header file and theexterndeclaration in the C file.You have to put the definition (full body) in the header file, this will allow any file which includes the header file to be able to use the inline definition if the compiler chooses to do so.
You have to put the
externdeclaration (prototype) in the source file to tell the compiler to emit an extern version of the function in the library. This provides one place in your library for the non-inline version, so the compiler can choose between inlining the function or using the common version.Note that this may not work well with the MSVC compiler, which has very poor support in general for C (and has almost zero support for C99). For GCC, you will have to enable C99 support for old versions. Modern C compilers support this syntax by default.
Alternative:
You can change the header to have a
static inlineversion,However, this doesn’t provide a non-inline version of the function, so the compiler may be forced to create a copy of this function for each translation unit.
Notes:
The C99 inlining rules are not exactly intuitive. The article “Inline functions in C” (mirror) describes them in detail. In particular, skip to the bottom and look at “Strategies for using inline functions”. I prefer method #3, since GCC has been defaulting to the C99 method for a while now.
Technically, you never need to put
externon a function declaration (or definition), sinceexternis the default. I put it there for emphasis.