I had a discussion with Johannes Schaub regarding the keyword inline.
The code there was this:
namespace ... {
static void someFunction() {
MYCLASS::GetInstance()->someFunction();
}
};
He stated that:
Putting this as an inline function may
save code size in the executable
But according to my findings here and here it wouldn’t be needed, since:
- [Inline] only occurs if the compiler’s cost/benefit analysis show it to be profitable
- Mainstream C++ compilers like Microsoft Visual C++ and GCC support an option that lets the compilers automatically inline any suitable function, even those not marked as inline functions.
Johannes states that there are other benefits of explicitly specifying it, which I do not understand. For instance, he stated that
[..] "inline" allows you to define the function multiple times in the program.
.. which I am having a hard time understanding (and finding references to).
So
- Is
inlinejust a recommendation for the compiler? - Should it be explicitly stated when you have a small function (I guess 1-4 instructions?)
- What other effects are there when writing
inline? - is it needed to state
inlinein order to reduce the executable file size, even though the compiler should find such functions itself?
Is there anything else I am missing?
Yes.
For example from MSDN:
Note though:
[Note: Emphasis mine]
A TU is basically a set of headers plus an implementation file (
.cpp) which leads to an object file.Absolutely. Why not help the compiler help you generate less code? Usually, if the prolog/epilog part incurs more cost than having it inline force the compiler to generate them? But you must, absolutely must go through this GOTW article before getting started with inlining: GotW #33: Inline
namespaces can beinlinetoo. Note that member functions defined in the class body itself are inline by default. So are implicitly generated special member functions.Function templates cannot be defined in an implementation file (see FAQ 35.12) unless of course you provide a explicit instantiations (for all types for which the template is used — generally a PITA IMO). See the DDJ article on Moving Templates Out of Header Files (If you are feeling weird read on this other article on the
exportkeyword which was dropped from the standard.)Again, as I said, as a good programmer, you should, when you can, help the compiler. But here’s what the C++ FAQ has to offer about
inline. So be wary. Not all compilers do this sort of analysis so you should read the documentation on their optimization switches. E.g: GCC does something similar:Most compilers allow you to override the compiler’s cost/benefit ratio analysis to some extent. The MSDN and GCC documentation is worth reading.