0

I am writing a simple code trying to read 2d vector by using template. But get error like:

Severity Code Description Project File Line Suppression StateError LNK2019 unresolved external symbol

My main.cpp is like:

#include "header\\read_2d.h"
#include <iostream>  
#include <fstream>
#include <vector>
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{
    //input image array parameters and initialize a 2D array
    int nx = 200;
    int ny = 200;
    std::vector<std::vector<unsigned char> > image(nx, std::vector<unsigned char>(ny));
    std::vector<std::vector<unsigned char> > mask(nx, std::vector<unsigned char>(ny));
    string disk_filename = "disk.dat";

    //read image
    read_2d<unsigned char>(disk_filename, image);

    return 0;

}

My read_2d.h file is:

#ifndef READ_2D_H    // To make sure you don't declare the function more than once by including the header multiple times.
#define READ_2D_H


#include <iostream>  
#include <fstream>
#include <vector>
#include <string>
using namespace std;

template <typename myType>
void read_2d(string filename, vector< vector<myType> >& image);

#endif

My read_2d.cpp is:

#include "..\\header\\read_2d.h"
using namespace std;

template <typename myType>
void read_2d(string filename, vector<vector<myType> >& image)
{

    int nx = image.size();
    int ny = image[0].size();
    int sizeOfData = nx*ny*sizeof(myType);
    std::vector<char> raw_data(sizeOfData);
    std::ifstream inputFile;

    inputFile.open(filename.c_str(), ios::binary);

    if (inputFile.is_open()) {
        inputFile.read(&raw_data[0], sizeOfData);
        inputFile.close();

        for (int i = 0; i < nx; i++) {
            memcpy(&image[i][0], &raw_data[(i*ny)*sizeof(myType)], ny*sizeof(myType));
        }

    }
    else {
        cerr << "Input file for " << filename << " could not be opened...\n" << endl;
        exit(EXIT_FAILURE);
    }

}

Can any one help me point out what I have done wrong? Any comments will be very much appreciated!

  • Which part of the code produces the problem? – L. Kue Jun 27 '18 at 23:38
  • 1
    Also worth a read: [Why is "using namespace std" considered bad practice?](//stackoverflow.com/q/1452721) – Baum mit Augen Jun 27 '18 at 23:39
  • @L.Kue Not quite sure. The problem happened when I tried to compile the main code. LNK2019 unresolved external symbol "void __cdecl read_2d(class std::basic_string,class std::allocator >,class std::vector >,class std::allocator > > > &)" (??$read_2d@E@@YAXV?$basic_string@DU?$char_traitsV?$allocator std@@AAV?$vectorV?$vector@EV?$allocatorV?$allocator@V?$vector@EV?$allocator) referenced in functio – RealHala Jun 28 '18 at 03:18

0 Answers0