0

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
Community
  • 1
  • 1
SacGax
  • 157
  • 4
  • 10
  • See http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix/12574417#12574417 – Luchian Grigore Oct 20 '12 at 17:48

2 Answers2

1

Templates should instantiated by compiler before they used. In median.h you have declaration of median template, and in media.cpp you have its implementation but you don't use it in that file, so template won't instantiated in that file. On other side on main.cpp you 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 to median.h or instantiate the template in median.cpp by using:

template double median<double>(double*, size_t);
BigBoss
  • 6,904
  • 2
  • 23
  • 38
0

You can either put an #include "median.cpp" into your main or move the implementation of the template into the header file median.h

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • Include a cpp file? That's one of the worst advises you can give. – Luchian Grigore Oct 20 '12 at 17:54
  • I don't see it as a cpp file, rather than a template implementation file. Care to elaborate, why you think so? A link would be fine, too. – Olaf Dietsche Oct 20 '12 at 17:57
  • @Olaf there is absolutely no point in separating template definitions from their declaration - if anything, it could get in the way of inlining when using an insufficiently smart compiler. – Cubic Oct 20 '12 at 18:05
  • @Cubic it makes code easier to read, so that's one reason, no matter how small you think it is. – Seth Carnegie Oct 20 '12 at 18:06
  • 1
    @OlafDietsche then it should be renamed to `.template` or something so that it doesn't get accidentally sent to the compiler as a compilation unit. – Seth Carnegie Oct 20 '12 at 18:06