Reputation: 83
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.
#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
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);
}
#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);
}
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.
Upvotes: 2
Views: 501
Reputation: 992707
When compiling code that calls a template
function, the compiler must be able to see the full implementation of the function. At the point the compiler is building pa2.cpp
, the compiler is only looking at FileSystem.h
and the definitions within the header file (and other header files included from pa2.cpp
, of course). It does not look at the contents of FileSystem.cpp
at that point.
To fix this, move the implementation of FileSystem::fillArrayFromFile()
to the header file instead of the .cpp
file. You can do that one of two ways:
class FileSystem {
public:
template <class T>
void fillArrayFromFile(T list[], int size);
};
template <class T>
void FileSystem::fillArrayFromFile(T list[], int size)
{
// ...
}
or
class FileSystem {
public:
template <class T>
void fillArrayFromFile(T list[], int size)
{
// ...
}
};
Upvotes: 1