jeudi 20 juillet 2017

ODR violation with template specializations

We have a header file which contains some residuals for various floating point precisions:

template <typename T>
struct rsdTarget {
  static const double value;
};

template <>
const double rsdTarget<half>::value = (double)(1.0e-3);

template <>
const double rsdTarget<float>::value = (double)(1.0e-7);

template <>
const double rsdTarget<double>::value = (double)(1.0e-12);

This has worked because this header had only been included in a single compilation unit. Now I try to use this header in multiple compilation units and I get linker errors stemming from the ODR:

CMakeFiles/tests_g.dir/random_gauge.cc.o:(.rodata+0x108): multiple definition of `rsdTarget<double>::value'
CMakeFiles/tests_g.dir/clover_product.cc.o:(.rodata+0x548): first defined here

The initialization probably needs to go into a source file and be taken out of the header file. However it seems to be prohibited to but an extern in front of the const double.

What would I have to do such that this works with multiple compilation units?

Aucun commentaire:

Enregistrer un commentaire