Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline vs static inline in header file

To place an inline function definition in a C header file for a function that should be inlined into multiple other units, should inline or static inline be used? I've been Googling for a little while but there seems to be no concise explanation of the difference so far.

like image 327
Toby Avatar asked May 16 '14 15:05

Toby


1 Answers

The proper way to inline a function in C is as follows:

  • Place an inline function in the header
  • Create an implementation file that includes that header
  • Place an extern inline function in the implementation file.

example.h

inline int example(int val) {
    return (val << 2) | 1;
}

example.c

#include "example.h"

extern inline int example(int val);

Can't you just declare a static inline in the header, without .c?

This would result in separate independent function definitions in each translation unit from which the header is included. In addition in increasing the size of compiled code unnecessarily, this would produce some unexpected behavior when you obtain a pointer to your inline functions: rather than producing the same address, the addresses of the inline function taken in different translation units would produce different values.

but if one guards the header file the re-defining can be avoided, can't it?

No, absolutely not. This has nothing to do with multiple inclusions of the same header. Each translation unit is compiled separately from other translation units, so when the compiler sees a static function, it has no choice but to create a private duplicate invisible from the outside of the translation unit.

like image 177
Sergey Kalinichenko Avatar answered Sep 19 '22 00:09

Sergey Kalinichenko