H
here
I'm trying to complile and link this simple example of using a template:
//file stack2.hpp (header)
template<class T> class Stack {
T* v;
int max_size;
int top;
public:
class Underflow {};
class Overflow {};
Stack(int s); //constructor
~Stack(); //destructor
void push(T);
T pop();
};
//file stack2.cpp
#include "stack2.hpp"
template<class T> void Stack<T>:
ush(T c)
{
if (top==max_size) throw Overflow();
v[top] = c;
top = top + 1;
}
template<class T> T Stack<T>:
op()
{
if (top==0) throw Underflow();
top = top - 1;
return v[top];
}
//file user2.cpp
#include <iostream>
#include "stack2.hpp"
using namespace std;
Stack<char> sc(200);
int main(int argc, char *argv[])
{
sc.push('c');
cout << sc.pop() << "\n";
return 0;
}
/////////////////////////
If I compile with: g++ stack2.cpp user2.cpp
here's what I get:
/tmp/cciILMx2.o: In function `main':
user2.cpp
.text+0x1a): undefined reference to `Stack<char>:
ush(char)'
user2.cpp
.text+0x24): undefined reference to `Stack<char>:
op()'
/tmp/cciILMx2.o: In function `__static_initialization_and_destruction_0(int, int)':
user2.cpp
.text+0x94): undefined reference to `Stack<char>::Stack(int)'
user2.cpp
.text+0x99): undefined reference to `Stack<char>::~Stack()'
collect2: ld returned 1 exit status
//file stack2.hpp (header)
template<class T> class Stack {
T* v;
int max_size;
int top;
public:
class Underflow {};
class Overflow {};
Stack(int s); //constructor
~Stack(); //destructor
void push(T);
T pop();
};
//file stack2.cpp
#include "stack2.hpp"
template<class T> void Stack<T>:
{
if (top==max_size) throw Overflow();
v[top] = c;
top = top + 1;
}
template<class T> T Stack<T>:
{
if (top==0) throw Underflow();
top = top - 1;
return v[top];
}
//file user2.cpp
#include <iostream>
#include "stack2.hpp"
using namespace std;
Stack<char> sc(200);
int main(int argc, char *argv[])
{
sc.push('c');
cout << sc.pop() << "\n";
return 0;
}
/////////////////////////
If I compile with: g++ stack2.cpp user2.cpp
here's what I get:
/tmp/cciILMx2.o: In function `main':
user2.cpp
user2.cpp
/tmp/cciILMx2.o: In function `__static_initialization_and_destruction_0(int, int)':
user2.cpp
user2.cpp
collect2: ld returned 1 exit status