How does the linker handle identical template instantiations across translation units?

前端 未结 3 1535
遥遥无期
遥遥无期 2020-12-06 09:34

Suppose I have two translation-units:

foo.cpp

void foo() {
  auto v = std::vector();
}

bar.cpp

void bar         


        
3条回答
  •  再見小時候
    2020-12-06 10:39

    When you have a non-template class definition, for example, class Bar {...};, and this class is defined in the header, that is included in multiple translation units. After compilation phase you have two object files with two definitions, right? Do you think linker will create two binary definitions for the class in your final binary? Of course, you have two definitions in two translation units and one final definition in the final binary after the linkage phase is done. This is called linkage collapsing, it is not forced by the standard, the standard only enforces the ODR rule, that does not say how the linker resolves the final problem, it is up to the linker, but the only way I have ever seen is the collapsing way of resolution. Of course the linker can keep both definitions, but I cannot image why, since the standard enforces those definitions to be identical in their semantics (see the ODR rule link above for more details), and if those are not the program is ill-formed. Now imaging it was not Bar it was std::vector. Templates is just a way of code generation in this case, everything else is the same.

提交回复
热议问题