Suppose I have template code in MyHeader.h
, which is then included in 2 compilation units, A.cpp
and B.cpp
. Both of these files then instantiate the same template function, say f<int>();
(the latter defined non-inline in MyHeader.h
).
As far as I know, what's happening is the following. The compiler generates the code for f<int>();
in both A.obj
and B.obj
, then the liker discards one of the symbols at the linking stage.
My question: is this approach always "safe"? I.e., can there be linkers that will complain about duplicate symbols? Does the standard say anything about this? If yes, I cannot see any solution then to make all my template functions inline
.
This is always safe and covered by the ODR. §3.2/6:
There can be more than one definition of a […] non-static function template (14.5.6) […] in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. […long list…] If the definitions of
D
satisfy all these requirements, then the behavior is as if there were a single definition ofD
. If the definitions ofD
do not satisfy these requirements, then the behavior is undefined.
The requirement list that I skipped should be satisfied if you write sane code.
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