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<iostream>
#include<list>
using namespace std;
int main(){
list<int> arr(5);
for (int i=0;i<5;i++)
arr.push_back(i);
fun1();
fun2();
temp(arr);
return 0;
}
//a.h
#include <list>
using namespace std;
void fun1();
void fun2();
template <class L ,class A>
short temp(const list<L,A>& val);
//fun2.cpp
#include"a.h"
#include<iostream>
using namespace std;
void fun2(){
cout<<"I am in function2\n";
}
//a.cpp
#include "a.h"
#include<iostream>
using namespace std;
void fun1()
{
cout<<"I am in function1\n";
}
template <class L,class A>
short temp(const list<L,A>& val){
cout<<"inside the template function\n";
typename list<L,A>::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<iostream>
using namespace std;
void fun1()
{
cout<<"I am in function1\n";
}
template <class L>
short temp(const list<L>& val){
cout<<"inside the template function\n";
typename list<L>::const_iterator iter=val.begin();
while (iter != val.end())
{
cout<< *iter << endl;
++iter;
}
cout<<"leaving the template function\n";
return 0;
}
//a.h
#include <list>
using namespace std;
void fun1();
void fun2();
template <class L>
short temp(const list<L>& 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