* Win32 issues with Templates and Libs *

Sean Kelly sean at f4.ca
Tue Feb 20 08:44:02 PST 2007


Walter Bright wrote:
> The problem is that one of two kinds of COMDAT sections can be generated:
> 
> 1) Only one COMDAT with a particular name may appear
> 2) Any number of COMDATs with the same name may appear, pick one and 
> discard the others
> 
> Instantiating a template produces a COMDAT section. Since multiple 
> modules may instantiate a template with the same arguments, without 
> knowing about each other, option (2) is used.
> 
> When a module is put into a library, a dictionary is created for the 
> library, essentially an associative array of object modules indexed by 
> symbol names. COMDATs of option (1) get put into the dictionary, ones of 
> option (2) do not. Why not? Because if there's more than one of (2), 
> which object module do you pull in? No way to tell.

Let's back up for a second.  First, in the situation Kris mentioned, how 
many instances of Test!(char) exist altogether?  I had expected there to 
be two: one in test.lib and one in tester.obj.  But in this case I 
wouldn't expect the link error to occur, so perhaps you're saying that 
when the compiler sees "Test!(char) Global" in module test, it doesn't 
bother to create one in tester.obj?

Also, how do COMDATs differ from normal code blocks?  ie. Why is the 
linker able to resolve normal symbols in libraries but not templates? 
Wouldn't the symbol name in both cases be enough to sort things out?

> Thus, the problem you're seeing. The solution is:
> 
> 1) have another global in module test that gets pulled in, thus also 
> pulling the COMDAT along with it, and resolving the symbol.
> 
> 2) explicitly link in module test
> 
> So, you might ask, why not just regenerate the template instantiation 
> every time you use it? Because it would lead to a lot of object file bloat.

I guess this answers my question above: the compiler sees "Test!(char) 
Global" and doesn't bother to create another instance of the code.  But 
surely being able to create a functional application is preferable in 
this case.  Won't an optimizing linker throw out duplicates anyway?  Who 
cares if the object files are bloated, if that's the only workable 
option here?  Or perhaps this suggests the need for a D linker that 
builds a catalog of symbols inside libraries before linking instead of 
the behavior you describe above?


Sean



More information about the Digitalmars-d mailing list