I always try to keep implementation outside of headers, so for templates and inlined functions, I usually do something like this
// File.h
inline bool foo()
#include "File.hpp"
// File.hpp
inline bool foo()
{
return 1;
}
My question is, what does the C++ specification have to say about repeating the inline keyword for the actual implementation of the function? (as shown in this example)
I don't really want to do that as it gets messy with lots and lots of functions, and while my compiler doesn't complain, I wonder if the compiler still accepts the inline hint.
Anyone know?
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.
The decision to inline or not a function is made by compiler. And since it is made by compiler, so YES, it can be made at compile time only. So, if you can see the assembly code by using -S option (with gcc -S produces assembly code), you can see whether your function has been inlined or not. Save this answer.
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.
Static inline functions are simple. Either a function defined with the inline function specifier is inlined at a reference, or a call is made to the actual function. The compiler can choose which to do at each reference. The compiler decides if it is profitable to inline at -xO3 and above.
I tend to put inline
as far from the interface as possible since it is an implementation detail and not part of the interface. Hence: omit the first inline
in the declaration. And only attach it to the function definition. For the inclusion of an hpp compiler scopes are irrelevant in respect to inline since the files are treated as concatenated.
See also http://www.parashift.com/c++-faq/where-to-put-inline-keyword.html for a more detailed explanation.
It's OK, but putting inline
in the source file is even less of a hint, because the sources aren't generally visible to other translation units. If you implement the function outside the header, the compiler will probably not be able to inline it anyways.
The only practical use of inline
, in my opinion, is to prevent multiple definition of functions defined in the header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With