How to properly inline for static libraries

后端 未结 2 1010
南旧
南旧 2020-12-28 18:43

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.

<
相关标签:
2条回答
  • 2020-12-28 19:20

    You should define your function as static inline in the .h file:

    static inline float clampf( float v, float min, float max )
    {
        if( v < min ) v = min;
        if( v > max ) v = max;
    
        return v;
    }
    

    The function must be absent in the .c file.

    The compiler may decide not to inline the function but make it a proper function call. So every generated .o file may contain a copy of the function.

    0 讨论(0)
  • 2020-12-28 19:33

    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:

    1. 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.

    2. Technically, you never need to put extern on a function declaration (or definition), since extern is the default. I put it there for emphasis.

    0 讨论(0)
提交回复
热议问题