Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do compilers inline C++ code?

Tags:

In C++, do methods only get inlined if they are explicitly declared inline (or defined in a header file), or are compilers allowed to inline methods as they see fit?

like image 561
Tony the Pony Avatar asked Sep 18 '09 11:09

Tony the Pony


People also ask

When should you use inline in C?

Inline functions are commonly used when the function definitions are small, and the functions are called several times in a program. Using inline functions saves time to transfer the control of the program from the calling function to the definition of the called function.

Does the compiler automatically inline?

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 .

When might a compiler choose not to inline an function declared as inline?

The compiler can't inline a function if: The function or its caller is compiled with /Ob0 (the default option for debug builds). The function and the caller use different types of exception handling (C++ exception handling in one, structured exception handling in the other). The function has a variable argument list.

When was inline added to C?

Introduction. GNU C (and some other compilers) had inline functions long before standard C introduced them (in the 1999 standard); this page summarizes the rules they use, and makes some suggestions as to how to actually use inline functions.


1 Answers

The inline keyword really just tells the linker (or tells the compiler to tell the linker) that multiple identical definitions of the same function are not an error. You'll need it if you want to define a function in a header, or you will get "multiple definition" errors from the linker, if the header is included in more than one compilation unit.

The rationale for choosing inline as the keyword seems to be that the only reason why one would want to define a (non-template) function in a header is so it could be inlined by the compiler. The compiler cannot inline a function call, unless it has the full definition. If the function is not defined in the header, the compiler only has the declaration and cannot inline the function even if it wanted to.

Nowadays, I've heard, it's not only the compiler that optimizes the code, but the linker can do that as well. A linker could (if they don't do it already) inline function calls even if the function wasn't defined in the same compilation unit.

And it's probably not a good idea to define functions larger than perhaps a single line in the header if at all (bad for compile time, and should the large function be inlined, it might lead to bloat and worse performance).

like image 188
UncleBens Avatar answered Oct 09 '22 15:10

UncleBens