我在头文件中包含了模板函数声明,函数的定义写在.cpp文件中

时间:2018-02-19 13:25:06

标签: c++ c++11 c++14

我在.h文件中声明了一个模板函数,并在.cpp文件中定义并从另一个.cpp文件中调用该函数。

我收到以下错误

/tmp/ccJg5vwy.o:在函数main': main.cpp:(.text+0x8f): undefined reference to短暂时间< int,std :: allocator< int> >(std :: __ cxx11 :: list> const&)'

collect2:错误:ld返回1退出状态

我的档案是:

// 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;
    }

我正在以下列格式编译文件

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

我不明白为什么会出现链接问题。

我也试过将a.cpp和a.h更改为以下格式,但我仍然收到错误

// 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);

在这种情况下错误是

/tmp/cce0eJj9.o:在函数main': main.cpp:(.text+0x8f): undefined reference to短暂时间&lt; int&gt;(std :: __ cxx11 :: list&gt; const&amp;)' collect2:错误:ld返回1退出状态

0 个答案:

没有答案
相关问题