I have a shared library (.so in Linux, .dll in Windows) that needs to access a static variable contained in whatever executable it is loaded with. This variable happens to be of a class template type, and within a namespace. Despite declaring the variable as "extern" (and on Windows, "__declspec(dllimport)"), VC10 gives an "unresolved external symbol" error for this variable when the DLL is linked. This seems strange to me, as it should indeed not be resolved, and instead left for load time.
The header:
// a header demonstrating MSVC-compatible linkage
#ifdef _MSC_VER
#ifdef I_AM_DLL
#define TO_DLL_LINKAGE __declspec( dllimport )
#else
#define TO_DLL_LINKAGE __declspec( dllexport )
#endif
#else // not MSVC
#define TO_DLL_LINKAGE
#endif
template<class T>
class TheClass
{
public:
TheClass(T t) : value_(t) {}
T value() const
{
return value_;
}
private:
T value_;
};
typedef TheClass<int> MyClass;
and the DLL:
// a test library (DLL) for linkage experiment
#define I_AM_DLL
#include "theclass.hpp"
#include <iostream>
namespace foo {
extern TO_DLL_LINKAGE MyClass theObject;
}
void bar() {
int i = foo::theObject.value();
std::cout << "object value is " << i << std::endl;
}
the error:
error LNK2001: unresolved external symbol "_declspec(dllimport) class TheClass foo::theObject" (_imp_?theObject@foo@@3V?$TheClass@H@@A)
I suppose it goes without saying that this works fine in gcc. I have also reviewed a number of similar StackOverflow questions, but they either recommend what I'm already doing, or don't apply for various reasons (e.g. exporting instead of importing, a class instead of a class instance, etc.).
What additional magic do I need to make MSVC10 happy? Thanks.