Inline Functions in C: Difference between revisions

m
Bot: Replace deprecated source tag with syntaxhighlight
[unchecked revision][unchecked revision]
(Solution for inlining functions for every optimization option.)
 
m (Bot: Replace deprecated source tag with syntaxhighlight)
 
(3 intermediate revisions by one other user not shown)
Line 1:
In C (at least with GCC) 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 codenamed references or entry points for themtheir 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: exampleexample1.h'''
<sourcesyntaxhighlight lang="c">
inline long something(long i)
{
return i + 2;
}
</syntaxhighlight>
</source>
 
'''File: exampleexample1.c'''
<sourcesyntaxhighlight lang="c">
#include <example"example1.h>"
extern inline long something(long i);
</syntaxhighlight>
</source>
 
This way, the compiler inlines the function if possible, but additionally createsallocates codea forname itor reference that points to the specific implementation, ifin case a call is needed when inlining is not possible.
 
== Solution 2 ==
 
'''File: example2.h'''
<syntaxhighlight lang="c">
static inline long something(long i)
{
return i + 2;
}
</syntaxhighlight>
 
This is another solution, adding the static keyword.
 
[[Category:C]]
[[Category:Languages]]