错误LNK2019:未解决的外部符号错误?

时间:2014-04-03 02:00:03

标签: c++ c++11

可以告诉我为什么我会收到这个错误。

模板头文件(prog.h):

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <functional> 
using namespace std;

#ifndef H_PROG
#define H_PROG

// data files

#define D1 "data1.txt"

#define INT_SZ 4    // width of integer
#define FLT_SZ 7    // width of floating-pt number
#define STR_SZ 12   // width of string

#define INT_LN 15   // no of integers on single line
#define FLT_LN 9    // no of floating-pt nums on single line
#define STR_LN 5    // no of strings on single line

// function and class prototypes

// stores items from input file into vector
template < class T > 
void get_list ( vector < T >&, const char* );

#endif

.cpp文件:

#include "prog.h"
#include <fstream>


template < class T >
void get_list ( vector < T >& vector1, const char* filename )
{
    ifstream infile;
    ofstream outfile;

    infile.open(filename);
    if(infile.fail())
    {
        cout<<"File did not open."<<endl;
    }
    else
    {
        T data;
        while(infile)
        {
            infile>>data;
            vector1.insert(data);
        }
    }
}

在我的主要功能中:

#include "prog.h"
#include <conio.h>

int main ( )
{
    vector < int >    v1;  
    vector < float >  v2;   
    vector < string > v3;  


    // first heap

    cout << "first heap - ascending order:\n\n";
    get_list(v1,D1);

    _getch();
    return 0;
}

当我尝试运行此操作时,我收到错误消息:

错误LNK2019:未解析的外部符号“void __cdecl get_list(class std :: vector&gt;&amp; char const *)”(?? $ get_list @ H @@ YAXAAV?$ vector @ HV?$ allocator @ H @函数_main

中引用了std @@@ std @@ PBD @ Z)

2 个答案:

答案 0 :(得分:3)

在main.cpp中,您只能看到prog.h中的get_list声明。没有看到prog.cpp中的定义,因此模板没有实例化。

您可以显式实例化您在prog.cpp中关注的类型的模板,也可以将get_list函数定义放入prog.h头文件中。

通常,您会将模板函数的定义放入头文件中,以便在使用时进行实例化。在你的情况下,这意味着将prog.cpp文件的内容移动到prog.h中,而不是在项目中有prog.cpp文件。

答案 1 :(得分:1)

您没有将main.cpp与other.cpp文件链接起来。 get_list的函数原型在prog.h中,但实际的定义不是。