Pages

Wednesday, February 8, 2012

"Undefined Reference" While Using Templates In C++

Did you get "collect2: ld returned 1 exit status" ??

If yes , then there is some linker's problem. Lets solve it.

I designed a template for one of my assignment , But I was unaware of "Declaring & Defining" fundamentals of templates in C++.

Here is some code :

//Add.h

#include "Basic.h"
using namespace std;
template <class T>
class Add{

        int x;
        int y;
        
public:
      Add(int x,int y);
      Dump();
};


Add.cpp

#include "Add.h"

template <class T>
Add<T>::Add(int x,int y):x(1),y(2){};


template <class T>
Add<T>::Dump(){
 cout<<x<<"  "<<y;
}

Output:
collect2: ld returned 1 exit status

Reason:
Templates are just a recipe , they are not code. In order to compile this code, it must be generated first, which needs to know templates definition & definition parameters which are passed to it. And compiler does not know about separate compilation (compiler doesn't know about anything about code outside of a file).

Solution:
Put the definitions in the header files itself :)


//Add.h

#include "Basic.h"
using namespace std;
template <class T>
class Add{

        int x;
        int y;
        
public:
      Add(int x,int y);
      Dump();
};

template <class T>
Add<T>::Add(int x,int y):x(1),y(2){};

template <class T>
Add<T>::Dump(){
 cout<<x<<"  "<<y;
}




No comments:

Post a Comment