Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GCC inline C++ functions without the 'inline' keyword?

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?

like image 236
Carl Seleborg Avatar asked Oct 26 '09 17:10

Carl Seleborg


People also ask

Does GCC automatically inline functions?

GCC automatically inlines member functions defined within the class body of C++ programs even if they are not explicitly declared inline .

Is inline keyword necessary?

No, that does not matter at all. There are cases where it is appropriate to use inline in a . cpp file. E.g. applying optimizations to code that is entirely implementation specific.

Can compiler ignore inline?

No matter how you designate a function as inline , it is a request that the compiler is allowed to ignore: the compiler might inline-expand some, all, or none of the places where you call a function designated as inline .

Does the compiler automatically inline functions?

At -O2 and -O3 levels of optimization, or when --autoinline is specified, the compiler can automatically inline functions if it is practical and possible to do so, even if the functions are not declared as __inline or inline .


2 Answers

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.

As noted in the comments below, these -Ox are actually compound settings that envelop multiple more specific settings, including inlining-related ones (like -finline-functions and such), so one can also describe the behavior (and control it) in terms of those more specific settings.

like image 75
AnT Avatar answered Sep 29 '22 15:09

AnT


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.

like image 45
Marcin Avatar answered Sep 29 '22 14:09

Marcin