[Solve] Linker problem or syntax problem?

Hello,

I'm trying to write my first class on C++.
So I have the following 3 files:

leftist_heap.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#ifndef LEFTIST_HEAP_H_
#define LEFTIST_HEAP_H_

template<typename T>
class Heap {

private:
	T *object;
	Heap *left, *right;
	int key;


public:
	Heap(T *object, int key);

	void insert(T* object, int key);
	T* min(void);

	// Gets and Sets
	void setObject(T*);
	T* getObject();

	void setKey(int);
	int getKey();
};

#endif 


leftist_heap.cc:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "leftist_heap.h"

#include <cstdlib>

template <typename T>
Heap<T>::Heap(T* object, int key) {
	this->object = object;
	this->key = key;

	this->left = this->right = NULL;
}

template <typename T>
T* Heap<T>::min() {
	return this->getT();
}

template <typename T>
int Heap<T>::getKey() {
	return this->key;
}

template <typename T>
void Heap<T>::setKey(int key) {
	this->key = key;
}

template <typename T>
void Heap<T>::setObject(T* object) {
	this->object = object;
}

template <typename T>
T* Heap<T>::getObject() {
	return this->object;
}


and main.cc:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

#include "leftist_heap.h"

int main() {
	int *i = new int(1);
	Heap<int> *heap;
	heap = new Heap<int>(i,1);
	return 0;
}


But when I compile it with this commands:

1
2
3
g++ -c main.cc -I ./ 
g++ -c leftist_heap.cc -I ./ 
g++ -o main main.o leftist_heap.o 


I get this error:

1
2
3
4
5
6
Undefined symbols for architecture x86_64:
  "Heap<int>::Heap(int*, int)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [main] Error 1


I believe my problem is in main.cc, but I can't understand why.

Solution:
I found my answer here: http://www.cplusplus.com/forum/articles/14272/
Last edited on
You cannot do that, you have to declare templates fully inline.

Wrong:
1
2
3
4
5
template<typename T>
struct Class
{
    Class();
};
Right:
1
2
3
4
5
6
7
8
template<typename T>
struct Class
{
    Class()
    {
        //...
    }
};
With templates you should never have a .cpp or .cc file, only a .hpp or .hh file.
Last edited on
Okay, now it's working.
But what happen when I want to declare a class like this

1
2
3
4
template<typename T>
class MyClass{
//...
}


into a header file, and the implementation of all methods goes into .cc/.cpp file, is that possible?
Thanks, both of you.
Topic archived. No new replies allowed.