Re: Template linking problem

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Harvey,

There is a difference between a declaration and a definition.

A declaration does not generate any code, or set aside any storage.
(Inlines and templates muddy the waters, since they do not generate any code
until instantiated.)

A definition produces something (code or storage).  (So does the
instantiation of an inline or template.)

For example, in C++, this declaration does not set aside any storage for the
int:

extern int foo;

If you tried to link to this foo, you'd get a missing symbol.

Likewise, a static inside a struct or class is a declaration, not a
definition.  It does not set aside any storage.  To set aside storage, you
have to do it explicitly.

Now to make things a bit confusing, sometimes people do this:

class Foo
{
public:
  static int const Bar = 3;
};

And they compile & run their code, and everything appears okay.  But it's
not quite, since that declaration actually does not have any storage set
aside for it.  The compiler doesn't complain because it optimizes the above
in the normal way, substituting the const value.  But to be correct, you
still need to explicitly set aside the storage in a .cpp file (and without
specifying the value which was set in the header):

int const Foo::Bar;

One way to tickle this is to take the address of Foo::Bar.  That will cause
the compiler to need to resolve the identifier at link time, and the linker
won't find it, and that will cause the link to fail.

HTH,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux