Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem Linknig when using templates

Status
Not open for further replies.

bilbobaggio

Technical User
May 17, 2005
7
GB
I am getting a linker error whe nusing templates. If i remove the templates from the following sample and make the num member of A an int by default i get no error.

I have header file (A.h):
template <class T>
class A {
public: A(): num(1) {}
~A() {}
void print();
private: T num;
};

..... and implemention file (A.cpp)
#include "A.h"
#include <iostream.h>
template <class T>
void A<T>::print()
{ cout << num << endl; }

When i compile a simple program
A<int> a;
a.print()

i get the following error:

error LNK2001: unresolved external symbol "public: void __thiscall A<int>::print(void)" (?print@?$A@H@@QAEXXZ)
 
You need to include a.h in main.cpp, so it knows to create the <int> version of your template.

--
 
When working with templates, nearly all compilers require you to put the implementation of the templated class or function in the header file. That means that you have to put the code from A.cpp inside A.h instead.

Another solution is to #include "A.cpp" at the bottom of A.h. Some people prefer to use the .inl (for inline) extension for these types of files.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top