small functions defined in header files: inline or static?

后端 未结 3 1983
盖世英雄少女心
盖世英雄少女心 2021-01-07 19:17

I have a number of small functions which are defined in a .h file. It is a small project (now) and I want to avoid the pain of having declarations and definitio

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-07 19:37

    Since the question is about C (not C++), inline means that

    1. You wish "that calls to the function be as fast as possible" (ISO9899-1999, 6.7.4(5)). The same paragraph also states that it is implementation-defined to which extent this suggestion is effective. In other words, it has little bearing and does not imply any inlining at all (in fact, non-inlining may quite possibly be faster due to instruction cache effects).
    2. there are some restrictions and special cases in combination with extern (ISO9899-1999, 6.7.4(6), for example an inline funciton with external linkage must be defined in the same compilation unit, and an inline definition allows an extern definition elsewhere without an error (which is not necessarily a good thing, because the two functions need not be functionally equivalent, and it is unspecified which one the compiler uses at any time!).

    The linker implications given by Heptic are required for C++, but not required by C (as far as I can tell). They are necessarily required by the "shall have the same address in all translation units" clause in ISO14882, 7.1.2(4). I am not aware of any similar clause in C99.
    However, since the entirely different languages C and C++ usually go through the same C/C++ compiler and linker, it likely works identically for C, anyway.

    So... how to answer your question? Use inline when you feel it's adequate. Be aware of the possible pitfalls of extern. Otherwise, leave it away and trust the compiler to do it right.

提交回复
热议问题