Ok! I wrote my first list class in C++ using templates. It worked great when I tried using it in a test program. However, when I tried to include it in a bigger project, I got linking errors that the list class members had undefined references (all of them that used templates). After doing some testing, I found that if the member code was in the same object file as the code that was using them, the compiler didn't complain. But when I used the members in a seperate object file there was undefined references. Here is an example:
Test.h:
Code:
template <class DataType>
class MyTestClass
{
public:
int Func(DataType &, int);
};
Test.cpp:
Code:
#include <iostream>
#include <string>
#include "test.h"
using namespace std;
template <class DataType>
int MyTestClass<DataType>::Func(DataType &Value, int Count)
{
int i;
for (i=0;i<Count;i++)
std::cout << Value;
}
int main(int argc, char **argv)
{
MyTestClass<string> Test;
Test.Func("Hello!", 5);
}
g++ -O3 -o test test.cpp
Now this works fine, compiling and working without errors (I haven't acctually tried, but you get the idea!
)
This however, doesn't work:
Template.cpp
Code:
#include "test.h"
template <class DataType>
int MyTestClass<DataType>::Func(DataType &Value, int Count)
{
int i;
for (i=0;i<Count;i++)
std::cout << Value;
}
Test.cpp
Code:
#include <iostream>
#include <string>
#include "test.h"
using namespace std;
int main(int argc, char **argv)
{
MyTestClass<string> Test;
Test.Func("Hello!", 5);
}
g++ -c -O3 -o template.o template.cpp
g++ -c -O3 -o test.o test.cpp
g++ -O3 -o test test.o template.o
This gives an error something like:
Undefined reference to MyTestClass<(some very long thing about the string class>::Func(DataType &Value, int) when [DataType = string]
What do I do to fix the issue?