templates in different files
Hi all,
My problem is as follows - (All info code/error etc listed below)
If I include code parts #1 & #2 in separate files then I get some linker errors (at the end).
If I include everything in the same file then everything runs ok.
Pllllleeeeeeeeeeaaaaaaaassssssseeeeeeee help.
Thanks.
Code part #1
Code:
#include <iostream>
using namespace std;
template <class T>
class Stack {
public:
Stack() : index(-1) {}
~Stack() {}
void push(T val);
T pop();
private:
T data[100];
int index;
};
Code part #2
Code:
template <class T>
void Stack<T>::push(T val)
{
// Increment index, then store
data[++index] = val;
}
template <class T>
T Stack<T>::pop()
{
// Retrieve, then decrement index
return data[index--];
}
The main
Code:
#include "stack.h"
int main()
{
// Template instantiation
Stack<int> stack;
int num;
int den;
int val;
cout << "Enter num: ";
cin >> num;
cout << "Enter den: ";
cin >> den;
stack.push(num);
stack.push(den);
val = stack.pop();
cout << "popped " << val << endl;
val = stack.pop();
cout << "popped " << val << endl;
return 0;
}
The error - link time
Code:
% g++ *.C
Undefined first referenced
symbol in file
Stack<int>::pop() /var/tmp/ccA5bKJ2.o
Stack<int>::push(int) /var/tmp/ccA5bKJ2.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
% ls *.C *.h
stack.C stack.h stackMain.C
%
The versions
Code:
% ld -V
ld: Software Generation Utilities - Solaris Link Editors: 5.8-1.275
% g++ -v
Reading specs from /usr/local/lib/gcc-lib/sparc-sun-solaris2.7/3.0.4/specs
Configured with: ../gcc-3.0.4/configure
Thread model: posix
gcc version 3.0.4
%