Strange template "redefinition" linker error.

R

Robbie Hatley

I'd always thougth that a C++ compiler/linker should be able to
instantiate a template in mulitple places (say, in two different
translation units), even using the same template parameters so
that the resulting functions or classes are identical, without
causing any errors. Or so I thought.

But a few days ago, I added a couple of new template functions
to one of my personal library modules, and I got this linker
error message (from memory, as near as I can recall):

Linker Error: template std::string ConvertFromFfblk<std::string>
(ffblk const & FileBlock) redefined in MyProgram.cpp.
See original definition in rhutil.cpp.

The only place this template is defined in in a header, rhutil.h,
which is included in both translation units.

I was able to get the program to link by declaring the template
as "inline" in rhutil.h and recompiling rhutil.o before attempting
to recompile my program.

Is it normally necessary to declare a template function in a header
as being "inline"? Or is it just something in this particular case
that makes it necessary?

Perhaps the fact that a library module (a *.o file embedded in a
*.a file) instantiates this template has something to do with it?
If the compiler first compiles the non-library object module(s)
for a program (instantiating a template in the processs), then
attempts to link to a pre-exising library object module which
already contains an identical instantiation, could this cause
problems? Or should the compiler and linker be able to handle
that?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top