Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the compiler decide when to inline my functions (in C++)?

I understand you can use the inline keyword or just put a method in a class declaration ala short ctor or a getter method, but does the compiler make the final decision on when to inline my methods?

For instance:

inline void Foo::vLongBar()
{
   //several function calls and lines of code
}

Will the compiler ignore my inline declaration if it thinks it will make my code inefficient?

As a side issue, if I have a getter method declared outside my class like this:

void Foo::bar() { std::cout << "baz"; }

Will the compiler inline this under the covers?

like image 535
jkeys Avatar asked Jul 30 '09 07:07

jkeys


People also ask

Do compilers automatically inline functions?

Automatic function inlining and static 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 .

Why would a compiler decide not inline a function?

If the compiler decides that inlining the function will make the code slower, or unacceptably larger, it will not inline it. Or, if it simply cannot because of a syntactical dependency, such as other code using a function pointer for callbacks, or exporting the function externally as in a dynamic/static code library.

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.

Do compilers ignore inline?

Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining.


1 Answers

Yes, the final decision of whether or not to inline your code lies in the C++ compiler. The inline keyword is a suggestion, not a requirement.

Here are some details as to how this decision is processed in the Microsoft C++ Compiler

  • http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx
like image 157
JaredPar Avatar answered Oct 20 '22 22:10

JaredPar