If I include <string>
or <vector>
in multiple translation units (different .cpp
files), why doesn't it break the ODR?
As far as I know, each .cpp
is compiled differently, so std::vector
's member functions will be generated for each object file separately, right?
The linker should detect it and raise an error. Even if it doesn't (I suspect it's special case for templates), will it be reusing the same machine code, or a different set of cloned code in each translation unit, when I link all together?
The same way any template definitions don't break the ODR — the ODR specifically says that template definitions may be duplicated across translation units, as long as they are literally duplicates (and, since they are duplicates, no conflict or ambiguity is possible).
There can be more than one definition of a class type (Clause [class]), enumeration type ([dcl.enum]), inline function with external linkage ([dcl.fct.spec]), class template (Clause [temp]), non-static function template ([temp.fct]), static data member of a class template ([temp.static]), member function of a class template ([temp.mem.func]), or template specialization for which some template parameters are not specified ([temp.spec], [temp.class.spec]) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. [...]
- C++14 Standard, [basic.def.odr] p6
Multiple inclusions of <vector>
within the same translation unit are expressly permitted and effectively elided, more than likely by "#ifndef
" header guards.