Link to home
Start Free TrialLog in
Avatar of caibeier
caibeier

asked on

error LNK2001 and error LNK1120 when trying to compile and build the program

When I was trying to compile and build my program by MS VC++6, it gave me the following error:
-------------------------------------------
Linking...
Sort.obj : error LNK2001: unresolved external symbol "int __cdecl cmpNum(int,int)" (?cmpNum@@YAHHH@Z)
Debug/Sort.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
Sort.exe - 2 error(s), 0 warning(s)
-----------------------------------------------

I can see it has something to do with the function "cmpNum(int, int), but I don't know what's going wrong and how to resolve it, though everything seems fine for me. The following is some code of my program relating the function "cmpNum(int, int)" which is a template function and I need to pass it as a parameter into the "Sort" fuction. Any help will be really appreciated!!

template <class T>
int cmpNum(T t1, T t2);

template <class T, class S>
void Sort(T *s, T *e, S cmp);

int main()
{
      int nArray[4] = {2, 1, 0, 5};
      Sort(nArray, nArray + 4, cmpNum<int>);
      char *pcArray[6] = {"abc", "abcde", "a", "ab", "abcd", "abcdef"};
      Sort(pcArray, pcArray + 5, strcmp);
      return 0;
}
Avatar of AlexFM
AlexFM

Where is implementation of cmpNum function?
How about a templated class with a typedef for the cmp function. Something like,

template <class T>
class S
{
public:
      typedef int (*CMP)(T t1, T t2);
};

template <class T>
int cmp(T t1, T t2)
{
      return t1 == t2;
}

template <class T>
int Sort(T *s, T *e, S<T>::CMP pfn)
{
      return pfn(*s, *e);
}

int main()
{
      int nArray[4] = {2, 1, 0, 5};
      S<int>::CMP pfnInt = cmp<int>;
      Sort(nArray, nArray + 1, pfnInt);
      CString cstrArray[2] = {"awd", "dwg"};
      S<CString>::CMP pfnCString = cmp<CString>;
      Sort(cstrArray, cstrArray + 1, pfnCString);
      return 0;
}
Maybe you have not declared the .cpp file that contains cmpNum() function as a project file.
Then, your project is compiling properly because it founds .h file, but linking bad because the .cpp is not considered.
Template function implementation must be in the same cpp file or in h file included to it. Templated functions and classes are not subject of linking because they must be handled by compiler.
ASKER CERTIFIED SOLUTION
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of caibeier

ASKER

Thank you all! It worked! I really appreciate you times!! (O: