Why the linker complains about multiple definitions in this template?

overcoder picture overcoder · Oct 25, 2011 · Viewed 8.3k times · Source

This little piece of code triggers the linker's anger when included on at least two translation units (cpp files) :

# ifndef MAXIMUM_HPP
# define MAXIMUM_HPP

template<typename T>
T maximum(const T & a, const T & b)
{
    return a > b ? a : b ;
}

/* dumb specialization */
template<>
int maximum(const int & a, const int & b)
{
    return a > b ? a : b ;
}

# endif // MAXIMUM_HPP

But compiles and links fine with one translation unit. If I remove the specialization, it works fine in all situations. Here is the linker message :

g++ -o test.exe Sources\test.o Sources\other_test.o
Sources\other_test.o:other_test.cpp:(.text+0x0): multiple definition of `int maximum<int>(int const&, int const&)'
Sources\test.o:test.cpp:(.text+0x14): first defined here

Aren't templates allowed to be instantiated multiple times ? How to explain this error and how to fix it ?

Thanks for any advice !

Answer

Dani picture Dani · Oct 25, 2011

Its because complete explicit template specializations must be defined only once - While the linker allows implicit specializations to be defined more than once, it will not allow explicit specializations, it just treats them as a normal function.
To fix this error, put all specializations in source file like:

// header

// must be in header file because the compiler needs to specialize it in
// different translation units
template<typename T>
T maximum(const T & a, const T & b)
{
    return a > b ? a : b ;
}

// must be in header file to make sure the compiler doesn't make an implicit 
// specialization
template<> int maximum(const int & a, const int & b);

// source

// must be in source file so the linker won't see it twice
template<>
int maximum(const int & a, const int & b)
{
    return a > b ? a : b ;
}