[prog] C++ strange linking behaviour

Wolfgang Petzold petzold at villa-chaos.de
Mon Nov 8 18:09:13 EST 2004


Hi!

I have been trying to subclass an STL container in order to
add a method that can print its members nicely. So I entered
the three files below and compiled them with

	g++ -Wall -g -c -o main.o main.cxx
	g++ -Wall -g -c -o someclass.o someclass.cxx

No errors or warnings this far.

Trying to link them,

	g++ -o main main.o someclass.o

I have an error saying,

	undefined reference to `PrintableSet<int>::PrintableSet(void)'

The really strange thing about it is, if I copy the main() function
into the someclass.cxx file, compilation and linking work silently
and the resulting program prints "is: some string representation"
as expected.

The same thing holds for gcc-2.95.4 with linux (shown above),
gcc-3.3.1/mingw that comes with the dev-c++ IDE for W*n as well as
gcc-3.3.3/cygwin; although both the gcc-3 variants don't miss
PrintableSet(void) but PrintableSet(). So it isn't really compiler
dependent, is it?

Any ideas what I've been doing wrong here?

Thank you for your time,
regards
Wolfgang

-- someclass.h -------------------------------------------
#include <set>
#include <string>
using namespace std;

template <class Type>
class PrintableSet : public set<Type>
{
	public:
		PrintableSet();
		~PrintableSet();
		
		string as_string();
};

typedef PrintableSet<int> PrintableIntSet;
-----------------------------------------------------------

-- someclass.cxx ------------------------------------------
#include "someclass.h"

template <class Type>
PrintableSet<Type>::PrintableSet()
	: set<Type>()
{}

template <class Type>
PrintableSet<Type>::~PrintableSet()
{}

template <class Type>
string
PrintableSet<Type>::as_string()
{
	string representation;
	representation = "some string representation";
	return representation;
}
-----------------------------------------------------------

-- main.cxx -----------------------------------------------
#include <iostream>
using namespace std;

#include "someclass.h"

int
main()
{
	PrintableIntSet *is;
	is = new PrintableIntSet();
	cout << "is: " << is->as_string() << endl;
	return 0;
}
-----------------------------------------------------------

-- complete error message ---------------------------------
main.o: In function `__default_alloc_template<true, 0>::_Lock::_Lock(void)':
/usr/lib/gcc-lib/i386-linux/2.95.4/../../../../include/g++-3/stl_alloc.h:393:
undefined reference to `PrintableSet<int>::PrintableSet(void)'
/usr/lib/gcc-lib/i386-linux/2.95.4/../../../../include/g++-3/stl_alloc.h:393:
undefined reference to `PrintableSet<int>::as_string(void)'
collect2: ld returned 1 exit status
make: *** [main] Error 1
-----------------------------------------------------------




More information about the Programming mailing list