I just had a discussion with a coworker concerning code in header files:
He says that code defined in header files will always be inlined by the compiler (like the code from the function GetNumber() in my example header). I say it will be inlined sometimes, whenever the compiler decides to do so. So which one of us has to bring a cake to work for telling filthy lies? Or maybe we are both wrong...?
MyClass.hpp
class MyClass
{
public:
MyClass();
~MyClass();
int GetNumber() const
{
//...;
return m_number;
};
private:
int m_number;
};
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.
First, you cannot always inline, e.g. recursive functions might not be always inlinable (but a program containing a recursive definition of fact with just a printing of fact(8) could be inlined). Then, inlining is not always beneficial.
If you need to make sure that function is inlined and OK to go with proprietary extension in MS VC++, check out the __forceinline declarator. The compiler will either inline the function or, if it falls into the list of documented special cases, you will get a warning - so you will know the inlining status.
A static inline function is, in practice, likely (but not certain) to be inlined by some good optimizing compiler (e.g. by GCC when it is given -O2 ) at most of its call sites. It is defined in a header file, because it then could be inlined at most call sites (perhaps all of them).
Any function defined within the class (like your GetNumber example) rather than just declared is implicitly inline
. What that means is that it's equivilent to using the inline
keyword, so multiple inclusions of the header will not cause link errors due to multiple definitions of those functions.
Most modern compiler treat inline
as a linkage command and nothing more. Some compilers provide stronger keywords such as CL's __forceinline
which mean 'inline this if it's possible to do so'.
So you're both right and both wrong to a degree.
Your pal is wrong, you're right.
Inlining do not depends on where the code is (header or not). After preprocessing there is no headers or non-headers. Whole unit is a single file, it contains all included stuff.
Try running gcc preprocessor then you will see:
gcc -E some_source_file_with_includes
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