How can I tell gcc not to inline a function? - c

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?

You want the gcc-specific noinline attribute.
This function attribute prevents a
function from being considered for
inlining. If the function does not
have side-effects, there are
optimizations other than inlining that
causes function calls to be optimized
away, although the function call is
live. To keep such calls from being
optimized away, put
asm ("");
Use it like this:
void __attribute__ ((noinline)) foo()
{
...
}

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.

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:
Clang (check with __has_attribute(noinline))
Intel C/C++ Compiler (their documentation is terrible, but I'm
certain it works on 16.0+)
Oracle Solaris Studio back to at least 12.2
ARM C/C++ Compiler back to at least 4.1
IBM XL C/C++ back to at least 10.1
TI 8.0+ (or 7.3+ with --gcc, which will define __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:
__declspec(noinline)
static void foo(void) { }
PGI 10.2+ (and probably older) supports a noinline pragma which
applies to the next function:
#pragma noinline
static void foo(void) { }
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:
#pragma FUNC_CANNOT_INLINE;
static void foo(void) { }
In C, however, the function name is required:
#pragma FUNC_CANNOT_INLINE(foo);
static void foo(void) { }
Cray 6.4+ (and possibly earlier) takes a similar approach, requiring
the function name:
#pragma _CRI inline_never foo
static void foo(void) { }
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:
static void foo(void);
#pragma no_inline(foo)
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 \
HEDLEY_GNUC_HAS_ATTRIBUTE(noinline,4,0,0) || \
HEDLEY_INTEL_VERSION_CHECK(16,0,0) || \
HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
HEDLEY_TI_VERSION_CHECK(8,0,0) || \
(HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
# define HEDLEY_NEVER_INLINE __attribute__((__noinline__))
#elif HEDLEY_MSVC_VERSION_CHECK(13,10,0)
# define HEDLEY_NEVER_INLINE __declspec(noinline)
#elif HEDLEY_PGI_VERSION_CHECK(10,2,0)
# define HEDLEY_NEVER_INLINE _Pragma("noinline")
#elif HEDLEY_TI_VERSION_CHECK(6,0,0)
# define HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
#else
# define HEDLEY_NEVER_INLINE HEDLEY_INLINE
#endif
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 ☺.

A portable way to do this is to call the function through a pointer:
void (*foo_ptr)() = foo;
foo_ptr();
Though this produces different instructions to branch, which may not be your goal. Which brings up a good point: what is your goal here?

In case you get a compiler error for __attribute__((noinline)), you can just try:
noinline int func(int arg)
{
....
}

static __attribute__ ((noinline)) void foo()
{
}
This is what worked for me.

Use the noinline attribute:
int func(int arg) __attribute__((noinline))
{
}
You should probably use it both when you declare the function for external use and when you write the function.

I work with gcc 7.2. I specifically needed a function to be non-inlined, because it had to be instantiated in a library. I tried the __attribute__((noinline)) answer, as well as the asm("") answer. Neither one solved the problem.
Finally, I figured that defining a static variable inside the function will force the compiler to allocate space for it in the static variable block, and to issue an initialization for it when the function is first called.
This is sort of a dirty trick, but it works.

I couldn't get __attribute__((noinline)) to work, but this works on clang and GCC.
The Linux kernel defines noinline.
include/linux/compiler_attributes.h:#define noinline __attribute__((__noinline__))
#include <linux/kernel.h>
static noinline void foo(void);

Related

Is there a possibility to tell the gcc compiler to ignore function attributes? Or to speed up compilation time?

I don't have much experience with C and am now working on a HPC project which very often uses __attribute__ ((always_inline)) void foo() function definitions.
I see the point of doing it for performance runs, but for debugging, testing, and developing, the compilation time is way to long. Just earlier I wanted to add a simple printf in a function to see when the function is called, and had to wait 5min for it to compile.
Is there a possibility to pass gcc a flag to ignore the attribute requests? I already am compiling with the lowest level of optimization.
A hackish way of disabling the attribute might be to define it away in the preprocessor:
#define always_inline noinline
A better approach, however, would be to apply those attributes in a macro so that they can be configured globally, e.g.
#ifndef DEBUG
# define HOT_FUNCTION __attribute__ ((always_inline))
#else
# define HOT_FUNCTION /* nothing */
#endif
…
HOT_FUNCTION void foo() { … }

Looking for preprocessor command to remove command in code

I am working on a C library which sometimes uses
static inline void myfunc(...)
when defining a function.
Now I try to port this to an old C compiler that does not support "static inline". This is bcc - Bruce's C compiler.
Can I use a command in a header file that replaces
static inline void
with
void
in all programs that include this header file?
When you must target a compiler that does not support certain features, it is common to use macros in your code, rather than trying to modify your code with macros.
In this situation you can define STATIC_INLINE macro in a compiler-dependent way, and use it like this:
#ifdef BCC_COMPILER
#define STATIC_INLINE
#else
#define STATIC_INLINE static inline
#endif
...
STATIC_INLINE void myfunc(...)
Thank you very much to all for the help. I have to report that BLUEPIXY gave the answer that worked for me in his comment:
#define inline
Apparently bcc does accept static void but not static inline void.

Does Windows have a __declspec equivalent to Unix GCC's __attribute__((weak))?

I want to import some C code but override its main() function. I can do this in Unix by prefacing the C code's main declaration with __attribute__((weak)), however, this won't compile in Windows, because neither Strawberry Perl's GCC nor MinGW's GCC recognize __attribute__((weak)).
Reading the docs online, __declspec seems to function similarly. Is there a __declspec equivalent to Unix GCC's __attribute__((weak)) macro?
This is a more specific version of an earlier question I posted.
There's another way with MSVC that I think would work if you care to use it.
/*
* pWeakValue MUST be an extern const variable, which will be aliased to
* pDefaultWeakValue if no real user definition is present, thanks to the
* alternatename directive.
*/
extern const char * pWeakValue;
extern const char * pDefaultWeakValue = NULL;
#pragma comment(linker, "/alternatename:_pWeakValue=_pDefaultWeakValue")
See this old SO answer for some other options.
There's also __declspec(selectany)

What is the best way to suppress A "Unused variable x" warning? [duplicate]

This question already has answers here:
How can I suppress "unused parameter" warnings in C?
(12 answers)
Closed 4 years ago.
What is the best/neatest way to suppress a compiler (in this case GCC) like "Unused variable x" warning?
I don't want to give any certain flags to GCC to remove all these warnings, just for special cases.
(void) variable might work for some compilers.
For C++ code, also see Mailbag: Shutting up compiler warnings where Herb Sutter recommends using:
template<class T> void ignore( const T& ) { }
...
ignore(variable);
Do not give the variable a name (C++)
void foo(int /*bar*/) {
...
}
Tell your compiler using a compiler specific nonstandard mechanism
See individual answers for __attribute__((unused)), various #pragmas and so on. Optionally, wrap a preprocesor macro around it for portability.
Switch the warning off
IDEs can signal unused variables visually (different color, or underline). Having that, compiler warning may be rather useless.
In GCC and Clang, add -Wno-unused-parameter option at the end of the command line (after all options that switch unused parameter warning on, like -Wall, -Wextra).
Add a cast to void
void foo(int bar) {
(void)bar;
}
As per jamesdlin's answer and Mailbag: Shutting up compiler warnings.
I found an article, http://sourcefrog.net/weblog/software/languages/C/unused.html, that explains UNUSED. It is interesting that the author also mangles the unused variable name, so you can't inadvertently use it in the future.
Excerpt:
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*#unused#*/ x
#else
# define UNUSED(x) x
#endif
void dcc_mon_siginfo_handler(int UNUSED(whatsig))
If this is really what you want, you could use the unused attribute (GCC only), something like:
void foo(int __attribute__((__unused__)) bar) {
...
}
Not just for function parameters, of course, but that's the most common use case, since it might be a callback function for an API where you don't actually need all the input.
Additionally, GLib has a G_GNUC_UNUSED macro which I believe expands to that attribute.
You can silence the warning using #pragma
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused"
int unususedVariable = 1;
#pragma clang diagnostic pop
If you are using GCC, use #pragma gcc ...
#pragma unused <variable>
It's a very hackish solution, but try simply assigning the variable to itself.
I think that should fool most compilers into thinking that the variable is used. It should be quite portable too.
The cast to a void is the best approach because it shows that you didn't "accidentally" keep the variable in your code - ie: this function might be an instance where you have a table of function pointers that need the same parameter types and return types, but in this particular table entry you are not using the parameter.
That said, if you don't need it, get rid of it. ;)
Assign it to itself:
void f(int unused) {
unused = unused;
}
It works in GCC, but Clang needs -Wno-self-assign.
I think casting to void is the most portable solution: Both GCC and Clang understand this, even with full warnings -W{all,extra,pedantic}:
(void)unused;
Delete the unused variable declaration from the code (pun intended).
(What??? It's what I do: point that the obvious is most likely the best solution.)
Now, from comments on other answers, apparently it's garbage generated from macros. Well, that's a pleonasm.
Solutions:
refactor that macro to #if declare the variable only if it's really used;
create another version of the macro that skips the unused variable generation.
Better still, avoid using macros that bring issues to the code.
If it’s used and you are shipping the project, delete it. Worst, comment it.

#pragma inside #define

I'm working in a micro-controller using the C language. In this specific micro, the interrupts have to be defined using #pragma in following way:
static void func();
#pragma INTERRUPT func <interrupt_address> <interrupt_category>
static void func() { /* function body */ }
The <interrupt_address> is address of the interrupt in vector table. The <interrupt_category> is either 1 or 2. For example, to define an interrupt in Port 0 pin 0:
static void _int_p00();
#pragma INTERRUPT _int_p00 0x10 1
static void _int_p00() { (*isr_p00)(); }
We define actual interrupt service routine elsewhere and use function pointer (like isr_p00 in the example) to execute them.
It would be convenient if the interrupts could be defined using a macro. I want do define a macro in following way:
#define DECLARE_INTERRUPT(INT_NAME, INT_CAT) \
static void _int_##INT_NAME(); \
#pragma INTERRUPT _int_##INT_NAME INT_NAME##_ADDR INT_CAT \
static void _int_##INT_NAME() { (*isr_##INT_NAME)(); }
The compiler throwing the following error:
Formal parameter missing after '#'
indicating following line:
static void _int_##INT_NAME() { (*isr_##INT_NAME)(); }
I guess preprocessor directives cannot be used in #defines? Is there any work around?
C99 has the new _Pragma keyword that lets you place #pragma inside macros. Basically it expects a string as an argument that corresponds to the text that you would have give to the #pragma directive.
If your compiler doesn't support this (gcc does) and you'd go for an external implementation of what you need (as said, m4 could be a choice) the best would probably be to stay as close as possible to that not-so-new _Pragma. Then once your compiler builder catches up with the standard you could just stop using your script.
A workround is to use code generation or another macro language to preprocess your code.
ie write the code with a different extension.
Have your makefile or similar call the macro language (e.g. m4) or a script of some form to generate a .c file
Then compile that.
As far as I'm aware, what you are specifically asking is impossible. I'm presuming a preprocessor that works the same as the GNU C Preprocessor. In the manual for that, it states:
The compiler does not re-tokenize the preprocessor's output. Each preprocessing token becomes one compiler token.

Resources