You have it almost correct. You actually have it backwards; for inline functions you must put the inline
definition in the header file and the extern
declaration in the C file.
// mymath.h
inline float clampf( float v, float min, float max )
{
if( v < min ) v = min;
if( v > max ) v = max;
return v;
}
// mymath.c
#include "mymath.h"
extern float clampf( float v, float min, float max );
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 extern
declaration (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 inline
version,
// mymath.h
static inline float clampf(float v, float min, float max)
{
...
}
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 extern
on a function declaration (or definition), since extern
is the default. I put it there for emphasis.