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 definitions separate, because they change all the time. To avoid multiply-defined symbols, I can either have them static or inline. What should be preferred and why?
I know it is in general bad practice to define functions in headers. You don’t have to mention that in answers, this question is meant technically.
I’d use
static inline, butstaticwould work just as well.externandextern inlineare out because you’d get multiple external definitions if the header is included in more than one translation unit, so you need to considerstatic,static inlineandinlinespecification.Heptic correctly states in his answer that most compilers consider functions for inlining regardless of whether
inlineis specified or not, ie the main impact ofinlineis its effect on linkage.However,
staticdefinitions have internal linkage, so there’s not much difference betweenstaticandstatic inline; I preferstatic inlinefor function definitions in header files for purely stylistic reasons (rule of thumb: header files should only containexterndeclarations,static constvariable definitions andstatic inlinefunction definitions).inlinewithoutstaticorexternresults in an inline definition, which the standard states (C99 6.7.4, §6)ie inline definitions should always be accompanied by external definitions, which is not what you’re looking for.
Some more information about the subtleties of C99 inline semantics can be found in this answer, on the Clang homepage and the C99 Rationale (PDF).
Keep in mind that GCC will only use C99 semantics if
-std=c99or-std=gnu99is present…