Go to the first, previous, next, last section, table of contents.

I get undefined symbols when using templates

(Thanks to Jason Merrill for this section).

g++ does not automatically instantiate templates defined in other files. Because of this, code written for cfront will often produce undefined symbol errors when compiled with g++. You need to tell g++ which template instances you want, by explicitly instantiating them in the file where they are defined. For instance, given the files

`templates.h':

template <class T>
class A {
public:
  void f ();
  T t;
};

template <class T> void g (T a);

`templates.cc':

#include "templates.h"

template <class T>
void A<T>::f () { }

template <class T>
void g (T a) { }

main.cc:

#include "templates.h"

main ()
{
  A<int> a;
  a.f ();
  g (a);
}

compiling everything with g++ main.cc templates.cc will result in undefined symbol errors for `A<int>::f ()' and `g (A<int>)'. To fix these errors, add the lines

template class A<int>;
template void g (A<int>);

to the bottom of `templates.cc' and recompile.


Go to the first, previous, next, last section, table of contents.