Static data in DLL
c++, dll, linker, windows
Solution
In your application header file you need to do two things.
- When exporting, declare the definition `__declspec(dllexport)`
- When importing, declare the definition `__declspec(dllimport)`
You obviously cannot do them both at the same time.
What you have to do is define a macro like this:
#ifdef __COMPILING_MYLIB
#define MYLIBAPI __declspec(dllimport)
#else
#define MYLIBAPI __declspec(dllexport)
#endif
Then declare your exports like this:
// mylib.h
class MYLIBAPI MyClass {
public:
virtual ~MyClass();
static const QString JUST_A_NAME;
};
Then, when compiling MYLIB, you pass `-D__COMPLING_MYLIB` to the compiler, which triggers the `#if` above.
That way, when compiling the library itself, the header file declares things as exports, but when compiling things which will use the library, they are declared as imports.
Problem
My problem is remarkably similar to this one: A class in a DLL has a static member. In this case, the static member is of Type QString (a QT type) and provides a name for the class. I provide the normal export on class level: `__declspec(dllexport)`. When I link the DLL with my class to another project and try to compile it, I get an "unresolved external symbol" error for the static data. I verified two things: - Dumpbin definitely reports the static data member to be exported by compiled DLL. - Actually, the static data member seems not to be used in the application which reports the error. HEADER file (.h) in DLL is: ``` class __declspec(dllexport) MyClass { public: virtual ~MyClass(); static const QString JUST_A_NAME; }; ``` IMPLEMENTATION file (.cpp) in DLL is: ``` #include "MyClass.h" MyClass::~MyClass() { } const QString MyClass::JUST_A_NAME("call_me_al"); ``` In contrast to already mentioned post, I avoided methods to be inline, e.g. implementation is obviously not in the header. The type, QString (see line 83 ff.), contains several inlines itself. May that cause the error? EDIT: I added an import statement in the header of my application. It is located before any includes. HEADER file (.h) in APPLICATION is: ``` class __declspec(dllimport) MyClass { public: virtual ~MyClass(); static const QString JUST_A_NAME; }; ``` The error remains the same: ``` error LNK2001: non resolved external symbol ""public: static class QString const MyClass::JUST_A_NAME" (?JUST_A_NAME@MyClass@@2VQString@@B)". <name of .obj file from application> ```