Sunday 16 October 2016

c++ - I have included a template function declaration in a header file and the defintion of the function is written in the .cpp file

I have declared a template function in .h file and defined in a .cpp file and calling the function from another .cpp file.



i am getting the following error



/tmp/ccJg5vwy.o: In function main':
main.cpp:(.text+0x8f): undefined reference to
short temp < int, std::allocator < int > >(std::__cxx11::list > const&)'



collect2: error: ld returned 1 exit status




my files are:



//main.cpp



#include"a.h"
#include
#include
using namespace std;

int main(){

list arr(5);
for (int i=0;i<5;i++)
arr.push_back(i);
fun1();
fun2();
temp(arr);
return 0;
}



//a.h



#include 
using namespace std;
void fun1();
void fun2();
template
short temp(const list& val);



//fun2.cpp



#include"a.h"
#include
using namespace std;
void fun2(){
cout<<"I am in function2\n";
}



//a.cpp



#include "a.h"
#include
using namespace std;
void fun1()
{
cout<<"I am in function1\n";
}
template

short temp(const list& val){
cout<<"inside the template function\n";
typename list::const_iterator iter=val.begin();
while (iter != val.end())
{
cout<< *iter << endl;
++iter;
}
cout<<"leaving the template function\n";
return 0;

}


and i am compiling the files in the following format



g++ a.cpp fun2.cpp main.cpp



I am not getting why there is a linking problem.



I have also tried by changing a.cpp and a.h to the following format but still i am getting the error




//a.cpp



#include "a.h"
#include
using namespace std;
void fun1()
{
cout<<"I am in function1\n";
}

template
short temp(const list& val){
cout<<"inside the template function\n";
typename list::const_iterator iter=val.begin();
while (iter != val.end())
{
cout<< *iter << endl;
++iter;
}
cout<<"leaving the template function\n";

return 0;
}


//a.h



#include 
using namespace std;
void fun1();
void fun2();

template
short temp(const list& val);


in this case error is



/tmp/cce0eJj9.o: In function main':
main.cpp:(.text+0x8f): undefined reference to
short temp< int >(std::__cxx11::list > const&)'
collect2: error: ld returned 1 exit status

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...