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?

Recommended Answers

All 7 Replies

I am not sure, but i think you should try including

iostream too.

commented: Thanks for the attempt to solve. +1

try including iostream too.

No change.

i think you should try including
iostream too.

No need, theres no references to anything in iostream yet.

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.

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;
}

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.

commented: Good point! +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.