template instantiation with gcc 4.x

Volker (N) newsgroups@vsiep.de
Mon Aug 17 21:48:00 GMT 2009


Hi,

We have to port code to gcc 4.2.1 (linux), and most works well, except 
instantiation of templates in a dynamic library. I generated a minmal example 
to clearify my problem:

// ********** TemplateTest.H
#ifndef TESTCLASS
#define TESTCLASS

template <class X> class TestClass {
public:
  TestClass(const X &x) : m_x(x) {}
  X getX();
private:
  X m_x;
};
#endif

// ********* TemplateTest.cpp
#include "TestClass.H"

template <class X> X TestClass<X>::getX() {
  return this -> m_x;
}

template class TestClass<int>;

// *********** testMain.cpp
#include "TestClass.H"

int main(int argc, char **argv) {
  TestClass<int> a(4);
  a.getX();
  return 0;
}

So I compile (here as well, I took away all flags I think are not important 
here):
g++ -I. -c TestClass.cpp
g++ -shared -o libTestClass.so TestClass.o
g++ -I. -L. -lTestClass testMain.cpp

The first two commands work fine, but the compilation of testMain reveals (as 
the nm command does) that the symbols are not defined:

testMain.cpp:(.text+0x31): undefined reference to `TestClass<int>::getX()'

I read some information, like the gcc manual 
(http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Template-Instantiation.html#Template-Instantiation), 
but my attempts to follow the advises were without success.

Thanks to anybody who can make my example work without forcing the 
implementation of getX() to be compiled into any object using it or making 
getX inline. I know which instantiations I need (here just int) when building 
the library.

Greetings

Volker



More information about the Gcc-help mailing list