Inline Functions in C

From OSDev.wiki
Revision as of 21:12, 24 June 2017 by Rod (talk | contribs) (Solution for inlining functions for every optimization option.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

In C (at least with GCC) you can define inline functions for optimization purposes. The problem is that the linker will fail (with an undefined reference error) if no optimization option (e.g. -O2) is given to the compiler. That is because by default, with no optimization, the compiler doesn't inline functions, and as the compiler doesn't create code for them, the linker won't find them. Here is a possible solution that does not require defining the functions twice, and works for every optimization level. This is done by defining them in the header and declaring them as extern inline in the implementation file.

Solution

File: example.h

inline long something(long i)
{
  return i + 2;
}

File: example.c

#include <example.h>
extern inline long something(long i);

This way, the compiler inlines the function if possible, but additionally creates code for it, if needed when inlining is not possible.