error LNK2005: "double __cdecl str_to_T<double>()" already defined

I have the following function definition in a header guarded file called "lib_tools.h":

1
2
3
4
5
6
7
8
9
10
template<typename T>
T str_to_T(const char text_element []) {
	// assume integer
	return atoi(text_element);
}

template<>
double str_to_T<double>(const char text_element []) {
	return atof(text_element);
}


However, when I try to compile I get the following linker errors:

1>main.obj : error LNK2005: "double __cdecl str_to_T<double>(char const * const)" (??$str_to_T@N@@$$FYANQBD@Z) already defined in fun_load_training_data.obj
1>main.obj : error LNK2005: "double __cdecl str_to_T<double>(char const * const)" (??$str_to_T@N@@YANQBD@Z) already defined in fun_load_training_data.obj
1>lib_tools.obj : error LNK2005: "double __cdecl str_to_T<double>(char const * const)" (??$str_to_T@N@@$$FYANQBD@Z) already defined in fun_load_training_data.obj
1>lib_tools.obj : error LNK2005: "double __cdecl str_to_T<double>(char const * const)" (??$str_to_T@N@@YANQBD@Z) already defined in fun_load_training_data.obj
1>struct_horizon_value.obj : error LNK2005: "double __cdecl str_to_T<double>(char const * const)" (??$str_to_T@N@@$$FYANQBD@Z) already defined in fun_load_training_data.obj
1>struct_horizon_value.obj : error LNK2005: "double __cdecl str_to_T<double>(char const * const)" (??$str_to_T@N@@YANQBD@Z) already defined in fun_load_training_data.obj


Now, fun_load_training_data.h/.cpp contain nothing more than a single function declaration (not for str_to_T of course), and a #include of lib_tools.h (where str_to_T is defined). lib_tools.h is properly header guarded (checked it thrice), so what else could be causing this issue? I tried a clean/rebuild but that didn't help...
Not sure but maybe you have to put the definition of str_to_T<double> in a source file or declare it as inline.
Yes, explicitly instantiating a template means is can be multiply defined.
+1 Peter

Once you specialize it, it's no longer a template and is an actual function. Therefore normal function rules apply (inline or have the body in only one source file)
Hmm interesting, I didn't put them in a source file because they're templates, but inlining them fixed the errors. Do you know why?
Inline functions are allowed to be multiply defined because the compiler needs the function body in the source file that is calling it in order to inline it.
Makes sense, thanks :)
Topic archived. No new replies allowed.