Undefined reference to C++ template static data members

Axel Freyn axel-freyn@gmx.de
Mon Jun 14 17:58:00 GMT 2010

Hi Arthur,

On Thu, Jun 10, 2010 at 05:37:06AM -0700, awatt wrote:
> I have made a small bit of progress, when I changed
> template <class Service, class ServiceId, UOPT16 NumberOfServices> Service*
> ServiceManager<Service, ServiceId, NumberOfServices>::s_used = 0;
> To be
> template <> DiffservService*
> ServiceManager<DiffservService,DiffservServiceId,MAX_SERVICE_DS>::s_used =
> 0;
> The some error went away, however there are still errors with the static
> s_all array, the linker is not complaring about the non array static
> template members any more. But I am still left with a problem on
> template <> DiffservService 
> ServiceManager<DiffservService,DiffservServiceId,MAX_SERVICE_DS>::s_all[
> /cygdrive/s/ipw_products/sw_dev/common/pdc/tgt/rni/ose_ppc/./obj_app//pdc_rni.a(PDCProtocol.o):
> In function `ServiceManager<DiffservService, DiffservServiceId,
> 100ul>::release()':
> ../../../incl/ServiceManager.cxx:265: undefined reference to
> `ServiceManager<DiffservService, DiffservServiceId, 100ul>::s_all'
> ../../../incl/ServiceManager.cxx:265: undefined reference to
> `ServiceManager<DiffservService, DiffservServiceId, 100ul>::s_all'

It would help us very much if you could provide a small self-contained
test-program which reproduces your problem. What exactly are you trying
to achieve?
A problem I could imagine is, that you did not initialize the static
member "s_all" in your code. The following code compiles and runs fine
on my machine:

template <typename A> struct B
  static A c;
  static A d[6];
template <> int B<int>::c = 1;
template <> int B<int>::d[] = {0,1,2,3,4,5};
int main()
  std::cout << B<int>::c << " " << B<int>::d[2] << std::endl;

However, when I remove the two lines doing the initializations

template <> int B<int>::c = 1;
template <> int B<int>::d[] = {0,1,2,3,4,5};

I obtain the (correct) error about "undefined reference":

/tmp/ccopRcqM.o: In function `main':
t.cc:(.text+0x5d): undefined reference to `B<int>::d'
t.cc:(.text+0x63): undefined reference to `B<int>::c'
collect2: ld returned 1 exit status

Maybe you are missing the initialization of "s_all"?

(Just an additional remark: For constant static members, you can also
write "static const int c1 = 0;" directly in the class. Then you don't
need an external initialization)



More information about the Gcc-help mailing list