c++linker-errors

LNK2019 and LNK1120 with templated function


After having some problems with these two linker errors on SO, I have them again. However, this time the source seems to lie at another point.

compiler error shows that it cannot find a function with signature ""public: unsigned int __thiscall MyClass::myFunction<unsigned int>(int)const ".

However, moving the contents of myClass.cpp to main.cpp works. Don't know why (all other content of myClass.cpp doesn't have this problem. (other functions are not templated).

myClass.h

#ifndef X
#define X
class MyClass {
public:
    template<class T>
    T myFunction (int someArgument) const;
};
#endif

myClass.cpp

#include "myClass.h"
template<class T>
T MyClass::myFunction (int someArgument) const {
    return T();
}

main.cpp

#include "myClass.h"
int main () {
    MyClass a();
    a.myFunction<unsigned int>(42);
    return 0;
}

What can I do to fix this problem?


Solution

  • Because in main.cpp, the compiler can find the definition of the template function.

    Templates cannot be compiled, the compiler needs to be able to see the definition of the file, and it's can't see across files.

    Either include myClass.cpp in myClass.h, or just define everything in the header.