views:

645

answers:

5

Does GCC, when compiling C++ code, ever try to optimize for speed by choosing to inline functions that are not marked with the inline keyword?

+5  A: 

Yes, especially if you have a high level of optimizations enabled.

There is a flag you can provide to the compiler to disable this: -fno-inline-functions.

Marcin
Actually, -fno-inline-functions suppresses automatic inlining, and -fno-inline suppresses all inlining (source : http://gcc.gnu.org/onlinedocs/gnat_ugn_unw/Switches-for-gcc.html)
Samuel_xL
Ok, I'll update based on your comment, thanks for that.
Marcin
+13  A: 

Yes. Any compiler is free to inline any function whenever it thinks it is a good idea. GCC does that as well.

At -O2 optimization level the inlining is done when the compiler thinks it is worth doing (a heuristic is used) and if it will not increase the size of the code. At -O3 it is done whenever the compiler thinks it is worth doing, regardless of whether it will increase the size of the code. Additionally, at all levels of optimization (enabled optimization that is), static functions that are called only once are inlined.

AndreyT
+2  A: 

If you use '-finline-functions' or '-O3' it will inline functions. You can also use '-finline_limit=N' to tune how much inlining it does.

Chris Dodd
+1  A: 

"-O3 This option turns on more expensive optimizations, such as function inlining"

Ape-inago
they are expensive in that the function is essentially duplicated, sacrificing memory for speed.
Ape-inago
Adisak
*potentially expensive*
Ape-inago
+1  A: 

Yes, it does, although it will also generate a non-inlined function body for non-static non-inline functions as this is needed for calls from other translation units.

For inline functions, it is an error to fail to provide a function body if the function is used in any particular translation unit so this isn't a problem.

Charles Bailey