I have been encountering a linker error when attempting to call a class method from my main method. I have searched for an answer but nothing seems applicable to my issue, any help will be much appreciated.
FileSystem.h
#ifndef FILE_SYSTEM_H
#define FILE_SYSTEM_H
#include <fstream>
#include <string>
#include <random>
#include "SortingAlgorithms.h"
#include "SortingAlgorithms.cpp"
using namespace std;
class FileSystem
{
private:
ifstream inFile;
ofstream outFile;
template <class T>
void fillArrays( T randomArray[], T sortedArray[], T backwardArray[], int size );
public:
FileSystem();
~FileSystem();
bool openFile(string fileName);
void writeToFile(string output);
void createTestFiles(string testFiles[]);
template <class T>
void fillArrayFromFile(T list[], int size);
};
#endif
fillArrayFromFile
template <class T>
void FileSystem::fillArrayFromFile(T list[], int size)
{
int i;
for(i = 0; i < size; i ++)
{
inFile >> list[i];
}
inFile.clear();
inFile.seekg(inFile.beg);
}
pa2.cpp
#include <iostream>
#include <ctime>
#include <string>
#include <iomanip>
#include "TimerSystem.h"
#include "FileSystem.h"
using namespace std;
int main()
{
FileSystem file;
int testArray[10];
file.openFile("test-10-0.txt");
file.fillArrayFromFile(testArray, 10);
}
Error:
pa2.obj : error LNK2019: unresolved external symbol "public: void __thiscall FileSystem::fillArrayFromFile<int>(int * const,int)" (??$fillArrayFromFile@H@FileSystem@@QAEXQAHH@Z) referenced in function _main
C:\Users\Matt\Google Drive\Programming\Data Structures & Algorithms\PA2-9-15-2012\Debug\PA2.exe : fatal error LNK1120: 1 unresolved externals
Thanks again.
When compiling code that calls a
templatefunction, the compiler must be able to see the full implementation of the function. At the point the compiler is buildingpa2.cpp, the compiler is only looking atFileSystem.hand the definitions within the header file (and other header files included frompa2.cpp, of course). It does not look at the contents ofFileSystem.cppat that point.To fix this, move the implementation of
FileSystem::fillArrayFromFile()to the header file instead of the.cppfile. You can do that one of two ways:or