【问题标题】:error LNK2019: unresolved external symbol error?错误 LNK2019:未解决的外部符号错误?
【发布时间】:2014-05-14 14:56:24
【问题描述】:

谁能告诉我为什么会出现这个错误。

模板头文件(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 中引用

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

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

    【讨论】:

    • 我在 prog.h 文件中包含矢量。
    • using namespace std 也在那里.. 然后我在主函数中包含了#include "prog.h"
    • 如果缺少 #include &lt;vector&gt;using namespace std; 将导致编译器错误而不是链接器错误,尤其是问题中提到的错误。
    • @psj01,答案是固定的
    【解决方案2】:

    在 main.cpp 中,您只能看到 prog.h 中的 get_list 声明。 prog.cpp 中的定义是看不到的,所以模板没有被实例化。

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

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

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 1970-01-01
      • 2021-05-06
      • 2015-05-18
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多