[prog] C++ strange linking behaviour

Meredith L. Patterson mlp at thesmartpolitenerd.com
Tue Nov 9 10:04:11 EST 2004


Wolfgang Petzold wrote:
> That's for *template* classes only, right? If I include the
> implementation of non-template class methods more than once I will
> get a "multiple definition" error ...

This is what #ifndef wrappers are for. If you wrap your header file in 
preprocessor directives like

#ifndef _SOMECLASS_H
#define _SOMECLASS_H

[function prototypes go here]

#endif

then you can be assured that you won't define methods multiple times; if 
  somewhere in the compilation chain it turns out you have "someclass.h" 
included more than once, the first time it'll define the macro 
_SOMECLASS_H (which never expands into anything; you can safely think of 
it as a boolean value) and include the header, then the second time the 
preprocessor will see that _SOMECLASS_H has been defined, it'll skip 
down to the #endif, and you're safe. :)

Generally speaking, though, it's far more sanity-preserving to include 
the implementation of template methods within the header file. The STL 
and Boost both use this to excellent effect.

> Is there something like a "C++ one-liner of the month"-thing going on
> somewhere? Who said that /perl/ was the hard-to-read-language? OK, just
> kidding. But I'm impressed, really.

If you really want your mind bent, you might check out Alexandrescu's 
_Modern C++ Design_. That man does things with templates that I hadn't 
imagined were possible with anything, in a tiny amount of space.

Cheers,
Meredith


More information about the Programming mailing list