Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including template code in multiple compilation units, will it always link without inline?

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.

like image 633
vsoftco Avatar asked Mar 17 '23 01:03

vsoftco


1 Answers

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 of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.

The requirement list that I skipped should be satisfied if you write sane code.

like image 127
Columbo Avatar answered Apr 08 '23 07:04

Columbo