0
votes

Can any1 tell me why I'm getting this error.

template header file (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 file :

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

in the main function I have :

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

when i try to run this i get an error saying :

error LNK2019: unresolved external symbol "void __cdecl get_list(class std::vector > &,char const *)" (??$get_list@H@@YAXAAV?$vector@HV?$allocator@H@std@@@std@@PBD@Z) referenced in function _main

2

2 Answers

3
votes

In main.cpp you only have visibility to the get_list declaration in prog.h. The definition in prog.cpp is not seen and so the template is not instantiated.

You can either explicitly instantiate the template for the types you care about in prog.cpp or you can put the get_list function definition into the prog.h header.

Normally you would put the definition of a template function into a header file so that it can be instantiated when used. In your case that would mean moving the contents of the prog.cpp file into prog.h and not having a prog.cpp file in your project.

1
votes

You did not link the main.cpp with the other.cpp file. The function prototype for get_list is there in prog.h, but the actual definition is not.