This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Template linking problem
Harvey Chapman wrote:
> So, back to the original question, why do I have to specfically re-
> declare the static data member outside of the class header?
You aren't re-declaring it, you are defining it. Declaring and defining
are two different things, similar to the difference between providing a
prototype for a function and providing the body (implementation) of the
function. Only a definition actually tells the compiler to allocate
storage.
The reason that you don't have to do this with nonstatic members is
because they are created whenever you create an instance of the class,
and destroyed when that instance is destroyed. But static members are
like global variables, there is one singular copy that is shared by all
instances of the class. This is exactly what it means to have *static*
lifetime: the space for this variable is allocated at link time and the
variable remains valid from the very moment the program starts until it
terminates, regardless of how many instances of the class are created
and destroyed (which could be zero.) This is why you must declare
static members in *exactly* one translation unit -- you can't do it in a
header that is included multiple times. Get a book on C++ and read
about the One Definition Rule.
Brian