Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should an inline function be defined before it is called?

The C language allows source files to be read in a single pass without looking ahead; at any point the compiler only has to consider declarations, prototypes, macro definitions etc. that have appeared before its current position in the file.

Does this mean that for a function call to be inlined, a compiler might require the function to be defined before the call? For example:

int foo(void);
int bar(void) { return foo(); }
inline int foo(void) { return 42; }

Is the call to foo more likely to be inlined if the inline definition is moved in front of the definition of bar?

Should I arrange inline definitions in my code so that they appear before the calls that should best be inlined? Or can I just assume that any optimizing compiler that is advanced enough to do inlining at all will be able to find the definition even if it appears after the call (which seems to be the case with gcc)?

EDIT: I noticed that in the Pelles C with the /Ob1 option indeed requires the definition to visible before a call can be inlined. The Compiler also offers an /Ob2 option which removes this limitation (and also allows the compiler to inline functions without an inline specifier, similar to what gcc does), but the documentation states that using this second option may require much more memory.

like image 300
dpi Avatar asked Aug 21 '12 19:08

dpi


1 Answers

It shouldn't make any difference in practice. Because, its compiler's choice to inline a function or not even if it's explicitly told to inline. Compiler may also inline a function even if it's defined using inline keyword.

First, I ran your code with with gcc 4.6.3 without any optimizations:

$ gcc -fdump-ipa-inline test.c 

From the generated assembly both foo and bar are not inlined even though foo is inlined. When I changed put the definition of inline foo at the top, the compiler still didn't inline both.

Next I did the same with -O3:

$ gcc -fdump-ipa-inline -O3 test.c 

Now both the functions are inlined. Even though only one has the inline declaration.

Basically the compiler can inline a function as it sees fit.

like image 50
P.P Avatar answered Nov 01 '22 04:11

P.P