Hi,
Im learning C++ through 'The C++ Language Tutorial' by Juan Soulie and Ive reached the chapter on Template Functions. I've written up the example in visual studio 2008 and it works just fine.
I tried to modify the example by using multiple files and simply introducing a new template function in a separate .cpp file with its own header file that includes a prototype for that template function. If I try to call that funtion from my main() function I get an unresolved external link error with that function call.
If I omit that function then the program compiles and runs. If I copy and paste the template function above main then it compiles and runs just fine. I experimented and if I make the function a dedicated float function (getting rid of the template) in the secondary file then the program compiles and runs just fine. It is only when the secondary file has a template function then I get the external link error.
I would like to understand why this happens and how to correct this so that I can have a template function in a multiple file program. Here is my main code in the sources folder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
// function template
#include <iostream>
#include "functions.h"
using namespace std;
template <class T>
T GetMax(T a, T b)
{
T result;
result = (a>b) ? a : b;
return result;
}
int main()
{
int i = 5, j = 6, k;
long l = 10, m = 5, n;
float x = 10.43, y = 5.55, z;
k = GetMax(i, j);
n = GetMax <long> (l, m);
z = GetMax(x, y);
cout << k << endl;
cout << n << endl;
cout << z << endl;
cout << addValues(x, y) << endl;
cout << Subtract(x, y) << endl;
return 0;
}
|
the functions.h file in the header files folder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#ifndef FUNCTIONS
#define FUNCTIONS
#include <iostream>
using namespace std;
float addValues(float a, float b);
template <class Type>
Type Subtract(Type a, Type b);
#endif
|
and the function.cpp file in the sources file folder:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include "functions.h"
using namespace std;
float addValues(float a, float b)
{
return (a+b);
}
template <class Type>
Type Subtract(Type a, Type b)
{
Type result;
result = (a - b);
return result;
}
|
And here is the error (i ommited the truncation warnings from double to float for the first two float initialisations)
error LNK2019: unresolved external symbol "float __cdecl Subtract<float>(float,float)" (??$Subtract@M@@YAMMM@Z) referenced in function _main
1>I:\Files\Projects\Visual Studio Projects\C++ Online Tutorials\Chapter - Templates\Function Template\Debug\Function Template.exe : fatal error LNK1120: 1 unresolved externals