Say I have this small function in a source file
static void foo() {}
and I build an optimized version of my binary yet I don't want this function inlined (for optimization purposes). is there a macro I can add in a source code to prevent the inlining?
This is what worked for me.
In case you get a compiler error for
__attribute__((noinline))
, you can just try:You want the
gcc
-specificnoinline
attribute.Use it like this:
A portable way to do this is to call the function through a pointer:
Though this produces different instructions to branch, which may not be your goal. Which brings up a good point: what is your goal here?
I know the question is about GCC, but I thought it might be useful to have some information about compilers other compilers as well.
GCC's
noinline
function attribute is pretty popular with other compilers as well. It is supported by at least:__has_attribute(noinline)
)__TI_GNU_ATTRIBUTE_SUPPORT__
)Additionally, MSVC supports
__declspec(noinline)
back to Visual Studio 7.1. Intel probably supports it too (they try to be compatible with both GCC and MSVC), but I haven't bothered to verify that. The syntax is basically the same:PGI 10.2+ (and probably older) supports a
noinline
pragma which applies to the next function:TI 6.0+ supports a
FUNC_CANNOT_INLINE
pragma which (annoyingly) works differently in C and C++. In C++, it's similar to PGI's:In C, however, the function name is required:
Cray 6.4+ (and possibly earlier) takes a similar approach, requiring the function name:
Oracle Developer Studio also supports a pragma which takes the function name, going back to at least Forte Developer 6, but note that it needs to come after the declaration, even in recent versions:
Depending on how dedicated you are, you could create a macro that would work everywhere, but you would need to have the function name as well as the declaration as arguments.
If, OTOH, you're okay with something that just works for most people, you can get away with something which is a little more aesthetically pleasing and doesn't require repeating yourself. That's the approach I've taken for Hedley, where the current version of HEDLEY_NEVER_INLINE looks like:
If you don't want to use Hedley (it's a single public domain / CC0 header) you can convert the version checking macros without too much effort, but more than I'm willing to put in ☺.
GCC has a switch called
-fno-inline-small-functions
So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.