hi firedraco,
thank u for your fast answer !
ok, right. but i would really like to understand how it is working and not just that its working or why it has to work this way .. lets look at the two processes (compiling and linking) individual:
g++ -c -o main.o main.cpp
the compiler will see the template code (from include "helper.h") and store it to be able to produce real code later.
1 2 3 4 5 6 7
|
template<class Numeric>
std::string toString(Numeric num)
{
std::ostringstream stream;
stream << num;
return stream.str();
}
|
then the compiler goes on and finds a function call to the template code:
now the compiler produces the actual code for the function for integers.
1 2
|
std::string toString(int num)
{ ... }
|
and then the compiler is ready with main.cpp and has to store the produced code in the object file, including the code it produced for the template function.
g++ -c -o human.o human.cpp
so here the same thing happens again. it does not know anything about the code it has produced for main.o, consequently it will produce the same function code again, doesn't it?
=> i have two object files containing the same function, am i wrong ? the code has to be produced write now because we are ready with compiling and start linking:
g++ -o test main.o human.o
now the linker will see that there is a "std::string toString(int num);" function defined in both files, why doesn't he care (at this point it has to be an actual function, because the linker cant build one, its just a linker ..)? he doesn't know that these are templetes and even if he would know .. he still wouldn't know which function call he should link to which function implementation, would he?
u see my point? i dont understand how the linker can differ between these function because as far as i know after compilation a template is transformed to a "normal function"? please tell me which step in my little story is the broken one?
lg,
flowly