Reputation: 258618
I was attempting to prove that you need a definition for an inline
function in all TU's that use it. However, the following code compiles well (MSVS 2010):
inline void foo();
#include "inc.h"
void x();
int main()
{
foo(); // <--- compilation fails if I remove this call
x();
return 0;
}
void foo()
{
}
#include "inc.h"
void x()
{
foo();
}
Note the function calls are there to prevent optimizations. This compiles, although foo
is declared inline
and only defined in test.cpp
but is also used in test2.cpp
.
If I comment out the call to foo
in main()
, I get the expected error.
"void __cdecl foo(void)" (?foo@@YAXXZ) referenced in function "void __cdecl x(void)" (?x@@YAXXZ) fatal error LNK1120: 1 unresolved externals
Why does having the foo
call there matter? The code shouldn't work in either case, right?
Adding extern
to foo
's declaration in inc.h
also makes it compile (regardless of the call to foo
in main
).
Upvotes: 4
Views: 904
Reputation: 96291
This is very clear in 3.2/3:
...An inline function shall be defined in every translation unit in which it is used.
If you don't define it in every such TU then all bets are off and anything the compiler does is fine, including appearing to work in some cases and failing to work in others.
Upvotes: 2