I have a template class with a static member, for simplicity:
template<typename T>
struct A
{
static inline int x = 1;
};
But if I include the header with struct A definition in several shared-libraries, each of them will have its own instance of A<T>::x. And I would like to have the instance of A<T>::x (for some fixed list of T-types) only in some one shared library, and all other libraries accessing it.
In Visual Studio I can do it by writing in the header
#ifdef _WIN32
# ifdef MY_LIB_EXPORT
# define MY_LIB_API __declspec(dllexport)
# else
# define MY_LIB_API __declspec(dllimport)
# endif
#else
# define MY_LIB_API
#endif
template<typename T>
struct A
{
MY_LIB_API static int x;
};
and in a .cpp-file from the selected dynamic library:
template<> int A<SpecificType1>::x = 0;
template<> int A<SpecificType2>::x = 0;
…
But unfortunately, this way does not work with linux/clang, where in other .cpp-files I get:
error: instantiation of variable 'A<SpecificType1>::x' required here, but no definition is available
Is there a universal way for solving my task?