This is the mail archive of the
binutils@sourceware.org
mailing list for the binutils project.
Linking template instanciations in multiple translation units.
- From: Brendon Costa <brendon at christian dot net>
- To: binutils at sourceware dot org
- Date: Sat, 02 Dec 2006 11:01:45 +1100
- Subject: Linking template instanciations in multiple translation units.
Hi all,
I have come across some unexpected behavior with multiple different
template instantiations of the SAME template function in different
translation units. I am not sure if this code is actually valid, however
i came across it while compiling the GCC libstdc++ code.
The code below should demonstrate the problem.
If i use the code below which creates two different implementations of
the same template function instantiation, then no errors/warnings emit
during compiling or linking (I would have expected an error or warning
at the linking stage) but instead the implementation that takes effect
is always the first of the translation units provided on the command
line. For example:
g++ main.cpp test.cpp
prints:
Two
Two
and
g++ test.cpp main.cpp
prints:
One
One
I understand that GCC emits a separate instance of the template in each
translation unit it is required in and flags it so that the linker
should then handle the multiple implementations. Usually these template
implementations should be the same, however I came across this one that
was not. Should the linker check to see if the implementations that it
"merges" are the same or is this not possible or not meeting a
particular requirement?
Thanks,
Brendon.
-- main.cpp --
#include <iostream>
#undef SOME_DEFINE
#include "test.h"
int main()
{
Function1(3.0f);
Function2();
return 0;
}
-- test.cpp --
#define SOME_DEFINE
#include "test.h"
void Function2()
{
Function1(3.0f);
}
-- test.h --
#include <iostream>
template <typename T>
void Function1(T val)
{
#ifdef SOME_DEFINE
std::cout << "One" << std::endl;
#else
std::cout << "Two" << std::endl;
#endif
}
void Function2();