Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I have a median function that finds a median from elements of the array as follows
median.h
template <class N>
N median (N*,size_t);
median.cpp
#include "median.h"
template <class N>
N median (N* numbers,size_t size){
size_t mid = size/2;
return size % 2 == 0? (numbers[mid] + numbers[mid-1])/2 : numbers[mid];
}
main
#include <iostream>
#include "median.h"
using namespace std;
int main(){
double Numbers [] = {1,2,3,4,5,6,7};
size_t size = sizeof(Numbers)/sizeof(*Numbers);
double med = median(Numbers,size);
cout << med << endl;
return 0;
}
But I get the following error
main.obj : error LNK2019: unresolved external symbol "double __cdecl median<double>(double *,unsigned int)" (??$median@N@@YANPANI@Z) referenced in function _main
Templates should instantiated by compiler before they used. In
median.hyou have declaration ofmediantemplate, and inmedia.cppyou have its implementation but you don’t use it in that file, so template won’t instantiated in that file. On other side onmain.cppyou try to instantiate template but there is no implementation, just declaration! So compiler will fail to instantiate template’s implementation and that’s the cause of your error. Just move implementation tomedian.hor instantiate the template inmedian.cppby using: