c99 inline semantics with gcc (mspgcc)

后端 未结 2 1779
逝去的感伤
逝去的感伤 2021-02-10 15:57

I am writing a couple of functions that I would like to inline.

Reading here and using the second c99 inline option with inline on all declarations and definitions, like

2条回答
  •  北海茫月
    2021-02-10 16:39

    You have things exactly the wrong way around from the way you need them. In the header, you should use:

    inline void SPFD54124B_write_cmd(uint16_t command)
    {
        spi_write(command, CMD_WIDTH);
    }
    

    In the translation units that include this header, this will create an inline function with external linkage. In exactly one of these translation units you should also place the declaration:

    extern void SPFD54124B_write_cmd(uint16_t);
    

    This (together with the inline definition from the header) will create an external definition of the function. The other files that include the header but do not include the extern declaration will create an inline definition of the function: a definition only available in that translation unit, but that does not forbid an external definition elsewhere.

    In total you will have one external definition of the function, and each file that includes the header will also have a non-external definition available; the compiler can use either. Conceptually there is still just one function called SPFD54124B_write_cmd in the complete program - for example if you take the address of the function in multiple translation units you should get the same value.

    As an alternative, you can put this in the header:

    static inline void SPFD54124B_write_cmd(uint16_t command)
    {
        spi_write(command, CMD_WIDTH);
    }
    

    and use no extern declaration at all; this will create an inline function with internal linkage in each file that includes the header. There will be no external definition of the function at all, and conceptually each translation unit that includes the header has its own independent copy of the function.


    (It should be noted for posterity that GCC's current default mode is "gnu89", which does not implement C99 semantics for inline)

提交回复
热议问题