views:

333

answers:

2

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

  • tell the linker to share the static member class in the library?
  • use the static class members instantiated in the library in the main program?

PS. I use Visual Studio 2008...

A: 

Link the libarary statically instead of dynamically.

Or add a global function in the DLL that returns the values.

Kieveli
A: 

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.

balint.miklos