www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1995/02/07/21:52:49

Date: Tue, 7 Feb 1995 15:27:29 -0800 (PST)
From: Gordon Hogenson <ghogenso AT u DOT washington DOT edu>
To: Roland Exler <R DOT Exler AT jk DOT uni-linz DOT ac DOT at>
Cc: djgpp AT sun DOT soe DOT clarkson DOT edu
Subject: Re: Multiple definition ... using Templates

On Tue, 7 Feb 1995, Roland Exler wrote:

> Hi anybody,
> 
> I've an simple-looking error linking from multiple modules each using the
> same instance of a template-class. In the example below 'main' and 'sub'
> uses class 'store<int>' declared in file 'temp.h', both compile ok.
> 
> Linking the files produces the 'multiple definition'-error as you can see
> in the appended file 'ERR.LOG' produced by redirecting the output of make.
> 
> Can anybody tell me how to correct this error?
> 

This is a peculiarity of G++ 2.6.3.  There are several ways of getting
around this.

1.  Use a different version of G++.  2.6.0 will work correctly,
     as will the 'release of the day' compiler, available at
     ftp.cygnus.com:/pub/g++/rotd.tar.gz.  Also, get the file
     backend.diff.  With the source from G++ 2.6.3, and the "cp"
     directory from rotd.tar.gz, and these diffs (as well as the
     DJGPP diffs), you can build a compiler that works.  This is
     probably too much trouble, though, and gives you an 'unsupported'
     version of g++.

2.  Use the -fno-implicit-templates parameter.  Then in *one* of the
    modules, instantiate the templates explicitly by saying
    template class X<int>;  or 
    template ostream& operator<<( ostream& os, Vector<int>& vec);
    This can be excruciating, since you then have to know all of your
    instantiations, which might be a lot. 

3. Read the info files under 'template instantiation' (in the C++
   extensions chapter) for info about the '-fexternal-templates'
   option.  I have no experience with this option.  It may solve your
   problem more easily than the other methods.  It requires that you
   use #pragma interface on all files that use the template except
   one, in which you use #pragma implementation.  The template gets
   generated only for the one file.  You have to make sure that the
   templates are instantiated in that one file, or you will get 
   undefined symbols for them.

I mainly use method (2) except for cases where there a lot of templates.
In such cases I use -fno-implicit-templates on all files except one,
in which the templates get instantiated explicitly.

IMHO, this would all be better solved by a linker that glossed over
multiple definitions.  According to ANSI, multiple definitions are
technically errors, but the linker is not obliged to refuse to compile
because of them.

Gordon.




- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019