www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/09/24/09:15:25

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: template problems
Date: Mon, 22 Sep 1997 08:48:48 -0700
Organization: Alcyone Systems
Lines: 50
Message-ID: <34269360.6549C224@alcyone.com>
References: <34263F31 DOT 433CE30B AT cs DOT curtin DOT edu DOT au> <34265873 DOT 41C6 AT miage DOT isi DOT u-psud DOT fr>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Jean-Michel Brissiaud wrote:

> If your matric.cc file constains function's body, when you use it in
> multi-file projects, their body is defined each time.
> To solve your problem create an object matrix.o in compiling matrix.cc
> and include only matrix.h in your other .cc files.

It's not that simple with templates.  If you compile a template source
file, essentially no code will be generated.  The reason is because of
the way templates work:  You can think of them like macros (because
effectively, that's really what you are).  A template declaration
doesn't generate any executable code; it's when you _instantiate_ it
that it does.  And if you compile a template source file in isolation,
that can't happen.

Basically, the original poster is doing the right thing (including the
template's source file in each of the source files that use an
instantiation of it), but is dealing with the inevitable problem of
instantiation.

The "Template Instantiation" node of info gcc describes this situation. 
Basically, you have three options:

o   Just duplicate the code and don't worry about it.  This will
increase the size of your executable, but the code duplication linker
messages should be warnings, not errors.

o   Use explicit instantiation, where in _one_ source file, you include
the template file, and instantiate it.  All the other source files just
use the header of that source file, and often hide the template
instantiation behind a typedef.  The syntax for this looks something
like:

    template class T<int>;

where T is your template class.  This way the instantiation is done
once, and you don't have to worry about it again.

o   The third option involves weird #pragmas, and since I loathe
#pragmas, I've never really investigated it.

As I said, all this is described in info gcc.

-- 
          Erik Max Francis, &tSftDotIotE / mailto:max AT alcyone DOT com
                        Alcyone Systems / http://www.alcyone.com/max/
   San Jose, California, United States / icbm://37.20.07n/121.53.38w
                                      \
   "After each war there is a little / less democracy to save."
                                    / Brooks Atkinson

- Raw text -


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