0

I have three files (myClass.h, myClass.cpp, and main.cpp)

//
// myClass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_

template <class element_type>
class myClass
{
public:
	myClass();

	~myClass();
};

#endif /* MYCLASS_H_ */
//
// myClass.cpp

#include "myClass.h"

template <class element_type>
myClass<element_type>::myClass()
{

}


template <class element_type>
myClass<element_type>::~myClass()
{

}
//
// main.cpp


#include "myClass.h"

int main()
{
	myClass<int> classOBJ;


	return 0;
}

I tried compiling this in VC++ Express, Dev-Cpp, and Eclipse

All give me roughly the same error. From eclipse

undefined reference to `myClass<int>::~myClass()' main.cpp heapProj 15 C/C++ Problem
undefined reference to `myClass<int>::myClass()' main.cpp heapProj 12 C/C++ Problem

This leads me to believe that I'm coding something wrong, but I just can't track it down for some reason. What's the problem?

5
Contributors
7
Replies
8
Views
8 Years
Discussion Span
Last Post by Alex Edwards
0

That's got to be it, because I do know that if I stack them all together in one file, everything runs without a problem.

The only compiler I know of that actually allows this separation so far (in my studies) is the Sun Studio 12 "CC" compiler

That link is golden.

0

SOLUTION:
TWO files: myClass.h main.cpp

//
// myClass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_

template <class element_type>
class myClass
{
public:
	myClass();

	~myClass();
};

template <class element_type>
myClass<element_type>::myClass()
{

}


template <class element_type>
myClass<element_type>::~myClass()
{

}

#endif /* MYCLASS_H_ */
//
// main.cpp


#include "myClass.h"

int main()
{
	myClass<int> classOBJ;


	return 0;
}
1

SOLUTION:
TWO files: myClass.h main.cpp

//
// myClass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_

template <class element_type>
class myClass
{
public:
	myClass();

	~myClass();
};

template <class element_type>
myClass<element_type>::myClass()
{

}


template <class element_type>
myClass<element_type>::~myClass()
{

}

#endif /* MYCLASS_H_ */
//
// main.cpp


#include "myClass.h"

int main()
{
	myClass<int> classOBJ;


	return 0;
}

That's one way of doing it, but you could also use eager-inclusion.

// file.h
#ifndef MYHEADER_H
#define MYHEADER_H

/*Declaractions*/
#include "file.cpp"

#endif
// file.cpp
#ifdef MYHEADER_H


#endif
#include "file.h"

int main(){

   return 0;
}

And also instead of eager inclusion you can simply add the .cpp file later in the driver file, and include the header file in the driver file.

Votes + Comments
Good point!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.