我已经在头文件中包含了一个模板函数声明,而函数的定义是在.cpp文件中编写的。

26 浏览
0 Comments

我已经在头文件中包含了一个模板函数声明,而函数的定义是在.cpp文件中编写的。

我在.h文件中声明了一个模板函数,在.cpp文件中进行了定义,并在另一个.cpp文件中调用该函数。\n我遇到了以下错误:\n/tmp/ccJg5vwy.o: In function

main':
main.cpp:(.text+0x8f): undefined reference to

short temp < int, std::allocator < int > >(std::__cxx11::list > const&)\' \ncollect2: error: ld returned 1 exit status\n我的文件如下:\n//main.cpp\n

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

\n//a.h\n

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

\n//fun2.cpp\n

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

\n//a.cpp\n

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

\n我以以下格式编译文件\ng++ a.cpp fun2.cpp main.cpp\n我不明白为什么会出现链接问题。\n我还尝试了将a.cpp和a.h更改为以下格式,但仍然出现错误\n//a.cpp\n

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

\n//a.h\n

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

\n在这种情况下,错误是\n/tmp/cce0eJj9.o: In function

main':
main.cpp:(.text+0x8f): undefined reference to

short temp< int >(std::__cxx11::list > const&)\'\ncollect2: error: ld returned 1 exit status

0