Search code examples
cgccstaticinlinecompiler-optimization

Usage of static inline to functions which calls other larger functions in C


Say I have a function,

static inline int res( int x )
{
  /** total() is a large func */
  int processedPkts = total();
  return ( processedPkts + x);
}

int total()
{
   /** Where the function total() does lot of processing,counting no of packets 
    or say, it has many lines of code */
}

So, my question is, can I use static inline for res() function which in-turn calls larger functions?

As per my understanding on why/when to use inline,

it encourages the compiler to build the function into the code where it is used (generally with the goal of improving execution speed).

static inline is usually used with small functions that are better done in the calling routine than by using a call mechanism, simply because they are so short and fast that actually doing them is better than calling a separate copy.

So, at assembly level, total() function is unaffected (uses regular call mechanism) by static inline, and therefore it is recommended to use static inline for res() ?


Solution

  • It does not matter. The function total will not be probably inlined (normal function call will be emitted). Function res probably will be inlined.

    Why probably. Because the inline keyword is only a suggestion. Functions without inline may be inlined as well. The compiler may inline the total function as well if decides that on a certain level of optimization it will result in the best code generation.

    Many compilers have special extensions which give you control over inlining. for example:

    gcc has __attribute__((noinline)) and __attribute__((always_inline)).

    iar #pragma inline=never and pragma inline=force