In ISO C++ (non-member function)
It is OK only if the code actually appears in the header file as shown. It would be undefined behaviour (no diagnostic required) if the header file contains a non-inline declaration, but the inline
definition does not appear in all translation units; even if the function is not called.
Reference: C++14 [dcl.fct.spec]/4 (note that a definition is also a declaration):
If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears;
no diagnostic is required.
In ISO C++ (member function)
If the code appears inside a class definition, it is OK and the inline
keyword is redundant, since function definitions that appear inside a class definition are implicitly inline
.
If the class definition contained void fn();
and then there was an out-of-line definition inline void Class::fn() {
, the behaviour is the same as for the non-member case.
In ISO C
C11 6.7.4/7:
If all of the file scope declarations for a function in a translation unit include the inline
function specifier without extern
, then the definition in that translation unit is an inline definition.
The existence of a non-inline declaration means that the later definition is not an inline definition, despite the fact that it has the inline
keyword. So the definition is actually an external definition (i.e. same linkage properties as if it had not been marked inline
).
Therefore, if this code appears in a header file included by two translation units it is undefined behaviour due to multiple external definitions; but if the prototype is in a header and the definition is in one translation unit which includes that header, it is OK.
Note: GNU C inline
differs to ISO C inline
. I am unsure of the defined behaviour of this code in GNU C.
inline
is very different between the two.) – Madelon