Reputation: 1572
I know that the inline
keyword is only a hint for the compiler, and not forced (unless using __forceinline e.g. in MSVC).
Is it also the case when declaring the inlined function in header? In which compilation unit will the compiler put the code?
Upvotes: 1
Views: 1028
Reputation: 3225
inline
is not just a hint to the compiler.
An inline function may be defined in multiple translation units, and all of these definitions will have the same type, address, and definition.
If a function is defined in a header, then it must be declared inline
, or it will violate the One Definition Rule when it is included in multiple translation units.
An inline function is either:
inline
.class
/struct
/union
definition, whether it's a member function or a non-member friend function, is always inline.constexpr
is always inline.(source)
inline
is a hint] when declaring the inlined function in header?Yes. The inline
keyword is always a hint to the compiler to perform "inlining".
However, please note that this is only a hint. The compiler is free to ignore it (and many do).
The real reason compilers are able to perform inlining on inline functions is that the whole definition is available. You will notice the same inlining with static
functions and instantiated function templates.
Before linkage, the inline function will be fully defined in any compilation unit that defines it. It will be compiled in its entirety into each object file.
During linkage, the linker will determine which definition to use, and discard all the others.
See also this question and its answers.
Upvotes: 2
Reputation: 2606
Inline is not forced, ever. If you define a method inside the class definition, it is implicitly inlined. It's like defining it outside the class definition except with inline implied. This has nothing to do with what file the definition is in.
When a function you requested to inline is not actually inlined, it's up to the compiler to decide where to put it. In early days, you could get a non-exported copy in each file that header file was included in. Now, some strategy is applied like putting it in the same place as the first constructor, the first method, or where the virtual function table is. It's compiler-dependent.
Upvotes: 1
Reputation: 15522
The code will be present in all compillation units that include this header. The main point of inline
is saying to the linker that this function can be found in multiple object files and any of these copies can be chosen by linker.
Upvotes: 1