首页 文章

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

提问于
浏览
0

任何人都可以告诉我为什么我会收到这个错误 .

模板头文件(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>&,char const *)”(?? $ get_list @ H @@ YAXAAV?$ vector @ HV?$ allocator @ H @ std @@@ std @@ PBD @ Z)在函数_main中引用

2 回答

  • 1

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

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

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

  • 3

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

相关问题