Inline Functions in C: Difference between revisions

From OSDev.wiki
Jump to navigation Jump to search
[unchecked revision][unchecked revision]
Content added Content deleted
m (some rewording)
m (add another option)
Line 4: Line 4:
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.
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 ==
== Solution 1 ==


'''File: example.h'''
'''File: example1.h'''
<source lang="c">
<source lang="c">
inline long something(long i)
inline long something(long i)
Line 14: Line 14:
</source>
</source>


'''File: example.c'''
'''File: example1.c'''
<source lang="c">
<source lang="c">
#include "example.h"
#include "example1.h"
extern inline long something(long i);
extern inline long something(long i);
</source>
</source>


This way, the compiler inlines the function if possible, but additionally allocates a name or reference that points to the specific implementation, in case a call is needed when inlining is not possible.
This way, the compiler inlines the function if possible, but additionally allocates a name or reference that points to the specific implementation, in case a call is needed when inlining is not possible.

== Solution 2 ==

'''File: example2.h'''
<source lang="c">
static inline long something(long i)
{
return i + 2;
}
</source>

This is another solution, adding the static keyword.


[[Category:C]]
[[Category:C]]

Revision as of 20:42, 25 July 2017

In C you can define inline functions for optimization purposes. The problem is that the linker will fail (at least with GCC, 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 named references or entry points for their separate code, 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 1

File: example1.h

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

File: example1.c

#include "example1.h"
extern inline long something(long i);

This way, the compiler inlines the function if possible, but additionally allocates a name or reference that points to the specific implementation, in case a call is needed when inlining is not possible.

Solution 2

File: example2.h

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

This is another solution, adding the static keyword.