Reputation: 1887
I have a class like
class K {
static int a;
static int b;
}
I would like to create a shared library (dll) containing this class K
. In a cpp file compliled in the library I call
int K::a = 0;
int K::b = 0;
to instantiate the static variables. The dll does compile without errors, but when I use the library, I get the unresolved external symbol error for the members K::a
and K::b
. In the main program where I want to use it, I include the same header with the declaration of the class K
, the only difference is that for the library I use class __declspec( dllexport ) K { ... }
and for the main program class K { ... }
Probably I am doing more than one mistake so my questions would be, how can I
PS. I use Visual Studio 2008...
Upvotes: 3
Views: 2588
Reputation: 1887
One should use __declspec( dllimport )
in the header in the main application.
So here is the solution. The header file (included in both the library and the main application) is:
#ifdef COMPILE_DLL
#define DLL_SPEC __declspec( dllexport )
#else
#define DLL_SPEC __declspec( dllimport )
#endif
class DLL_SPEC K {
static int a;
static int b;
}
The cpp file in the library contains:
int K::a = 0;
int K::b = 0;
To compile the library one has to define the macro COMPILE_DLL, for the main application it shouldn't be defined.
Upvotes: 1
Reputation: 11075
Link the libarary statically instead of dynamically.
Or add a global function in the DLL that returns the values.
Upvotes: 0