locked
fatal error LNK1120: 2 unresolved externals RRS feed

  • Question

  • Hi , I wrote a template class and when I build it, I got the following compiling errors:

    1>------ Build started: Project: Review, Configuration: Debug Win32 ------
    1>Compiling...
    1>Review.cpp
    1>Linking...
    1>Review.obj : error LNK2019: unresolved external symbol "public: __thiscall TemplateTest<double>::~TemplateTest<double>(void)" (??1?$TemplateTest@N@@QAE@XZ) referenced in function "void __cdecl test_2(void)" (?test_2@@YAXXZ)
    1>Review.obj : error LNK2019: unresolved external symbol "public: __thiscall TemplateTest<double>::TemplateTest<double>(double,double,double,double)" (??0?$TemplateTest@N@@QAE@NNNN@Z) referenced in function "void __cdecl test_2(void)" (?test_2@@YAXXZ)
    1>C:\Documents and Settings\zhanzhex\My Documents\Visual Studio 2008\Projects\Review\Debug\Review.exe : fatal error LNK1120: 2 unresolved externals

    following is my code:

    TemplateTest.h

    template<typename T>
    class TemplateTest {
    private:
    	T a, b, c, d;
    	T max(T, T);
    public:
    	TemplateTest(T, T, T, T);
    	~TemplateTest(void);
    	T getMax();
    };

    TemplateTest.cpp

    #include "StdAfx.h"
    #include "TemplateTest.h"
    template<typename T>
    TemplateTest<T>::TemplateTest(T w, T x, T y, T z) : a(w), b(x), c(y), d(z) {}
    
    template<typename T>
    TemplateTest<T>::~TemplateTest(void){}
    
    template<typename T>
    T TemplateTest<T>::max(T a, T b) {
    	return (a > b)? a:b;
    }
    
    template<typename T>
    T TemplateTest<T>::getMax() {
    	return max(max(a, b), max(c, d));
    }

    Review.cpp:

    #include "stdafx.h"
    #include <iostream>
    #include "TemplateTest.h"
    
    void test_2();
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	test_2();
    	return 0;
    }
    
    void test_2() {
    	using namespace std;
    	TemplateTest<double> tt(2.8, 3.14, 1.38, 2.39);
    	//cout << "max(2.8, 3.14, 1.38, 2.39) : " << tt.getMax() << endl;
    }

    If I remove the statement 

    TemplateTest<double> tt(2.8, 3.14, 1.38, 2.39);

    from function test_2(), the program can be built successfully, but if I add the statement, I will get the compiling error message like above mentioned.

    what's this wrong?

    Sunday, May 27, 2012 2:32 AM

Answers

  • For class templates, the compiler needs to see the entire class definition to use it.

    In your case, the compiler only sees the contents of TemplateTest.h.

    You can overcome this by #including TemplateTest.cpp instead.

    But for class templates, it is always better to have the entire class definition in the .h file itself.

    This is how most of the template libraries like STL, Boost etc. are shipped.


    «_Superman_»
    Microsoft MVP (Visual C++)

    Polymorphism in C

    • Marked as answer by zhexin Sunday, May 27, 2012 4:47 AM
    Sunday, May 27, 2012 3:39 AM