25

I do have a class which looks like below:

//.h file
class __declspec(dllimport) MyClass
{
    public:
    //stuff
    private:

    static int myInt;
};

// .cpp file
int MyClass::myInt = 0;

I get the following compile error:

error C2491: 'MyClass::myInt' : definition of dllimport static data member not allowed

what should I do?

MBZ
  • 26,084
  • 47
  • 114
  • 191

3 Answers3

36

__declspec(dllimport) means that the current code is using the DLL that implements your class. The member functions and static data members are thus defined in the DLL, and defining them again in your program is an error.

If you are trying to write the code for the DLL that implements this class (and thus defines the member functions and static data members) then you need to mark the class __declspec(dllexport) instead.

It is common to use a macro for this. When building your DLL you define a macro BUILDING_MYDLL or similar. In your header for MyClass you then have:

    #ifdef _MSC_VER
    #  ifdef BUILDING_MYDLL
    #    define MYCLASS_DECLSPEC __declspec(dllexport)
    #  else
    #    define MYCLASS_DECLSPEC __declspec(dllimport)
    #  endif
    #endif

    class MYCLASS_DECLSPEC MyClass
    {
        ...
    };

This means that you can share the header between the DLL and the application that uses the DLL.

jaques-sam
  • 2,578
  • 1
  • 26
  • 24
Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
  • 1
    Here is the corresponding cite on [Microsoft's page](http://msdn.microsoft.com/de-de/library/8fskxacy.aspx): "Using __declspec(dllimport) is optional on function declarations [...]. However, you must use __declspec(dllimport) for the importing executable to access the DLL's public data symbols and objects. Note that the users of your DLL still need to link with an import library." – Jonny Dee Oct 09 '14 at 11:04
6

From MSDN Documentation,

When you declare a class dllimport, all its member functions and static data members are imported. Unlike the behavior of dllimport and dllexport on nonclass types, static data members cannot specify a definition in the same program in which a dllimport class is defined.

Hope it helps..

liaK
  • 11,422
  • 11
  • 48
  • 73
0

if you are importing a class you are importing it with all it members so it is impossible to define any class member on the "client side". dllexport keyword should be used on behalf of implementation dll

user396672
  • 3,106
  • 1
  • 21
  • 31