I am having this error message whenever I tried to compile
Error 6 error LNK2019: unresolved external symbol "void __cdecl MergeSort(class LinkedList<int> &)" (?MergeSort@@YAXAAV?$LinkedList@H@@@Z) referenced in function _main C:\Users\FOla Yinka\Documents\Visual Studio 2012\Projects\C++\C++\linkedlist.obj C++
Error 7 error LNK1120: 1 unresolved externals C:\Users\FOla Yinka\Documents\Visual Studio 2012\Projects\C++\Debug\C++.exe 1 1 C++
I have this in my header file
template<typename T>
class LinkedList{
protected:
public:
friend void MergeSort(LinkedList<T> &list);
};
template<typename T>
void MergeSort(LinkedList<T> &list){
}
To check if the fault is in the function declaration, I turned all the protected
members public
and I removed the friendship so MergeSort
can have access to all memebers and then the program compiled successfully. I don't know why I am having this error message.
The problem is that once your class template is instantiated for (say)
T=int
, thefriend
declaration declares the existence of a non-template function:In your code, this function does not exist. There is a function template called
MergeSort()
, but that is not the same thing you are declaring as afriend
.A possible solution is to define the
friend
within the class body:The other solution is to declare the
friend
before the class body so that it knows thefriend
is atemplate
:and then in the class body declare the
friend
like this:This C++ FAQ entry goes into the complete details of why you need a special work-around in this case.