7

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.

dpi
  • 1,919
  • 17
  • 17
  • You shouldn't. And soon all this inline crap will go away as LTO gets more popular. –  Aug 21 '12 at 19:33
  • I think this is a duplicate of [this Stack overflow question](http://stackoverflow.com/questions/9853318/c-inline-functions-methods) – Curious Aug 21 '12 at 20:13
  • @Curious: No, the question you linked is about C++. – netcoder Aug 21 '12 at 20:22

1 Answers1

3

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.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • But whether the compiler cares about the `inline` specifier or instead inlines whatever it wants has nothing to do with whether it can inline a function before its definition is visible. The latter requires the compiler to first go through the code and collect all function definitions, before deciding what to inline. The question remains if it is so common for compilers to do this that you can rely on it, and don't have to pay attention to the order of function definitions. – dpi Aug 22 '12 at 17:08