|
Prev: why are foos like vector<T>::size no duplicate symbols for linker?
Next: variable function in a template ?
From: Pavel Minaev on 28 Jun 2008 07:28 On Jun 28, 11:28 am, vl106 <vl...(a)hotmail.com> wrote: > { Please confine responses to standard C++ and generic concepts of compilation > and linking, i.e. not going overboard in environment-specific discussion. -mod } > > I have a question concerning the code the compiler > generates for template functions. > > - why does linker not complain about ctor being there 2-times? > - does linker "strip away" compiler generated template functions (if > necessary)? > - in MSVC map file: does "i" mean: internally created by compiler? > > 0002:00000990 ?f_a@@YAXXZ 00411990 f a.obj > 0002:000009c0 ??0?$ARRAY@H@@QAE@H@Z 004119c0 f i a.obj > 0002:00000a10 ?f_b@@YAXXZ 00411a10 f b.obj > > // a.cpp > #include "h.hpp" > void f_a() { > ARRAY<int> ia(3); > //... > > } > > // b.cpp > #include "h.hpp" > void f_b() { > ARRAY<int> ia(5); > //... > > } > > ARRAY is a minimalistic clone of std::vector. In a.cpp > and b.cpp I use the template class - and thus its (only) > function. > > Each .obj file has a definition of ARRAY<int>::ARRAY<int> > as can be seen from assembly files (see below). > > Why does linker not complain about duplicate symbols as > e.g. when I define "my_foo" both in a.cpp and b.cpp? > > b.obj : error LNK2005: "void __cdecl my_foo(void)" (?my_foo@@YAXXZ) > already defined in a.obj Typically, the compiler marks symbols generated from template instantiations in some special way which linker knows how to handle - for example, by discarding all similarly-named symbols except for the first one (if the One Definition Rule is followed, this behavior works as expected; if ODR is not followed, then Standard allows for undefined behavior anyway). The same technique is typically applied to inline member functions, which can otherwise also result in the same symbol being defined in object file produced from every compilation unit that used the inline function. For more detailed information on implementation details of this mechanism in most popular C++ implementations - which would be out of scope of this newsgroup - you might want to research on "COMDAT sections". -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |