Home > other >  __declspec(dllexport) on nested classes
__declspec(dllexport) on nested classes

Time:11-03

Code:

#ifdef BUILD_DLL
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif

class MY_API A
{
    public:
        void some_method();

    class B
    {
         public:
             void other_method();
    };
};

Do I have to add my macro (MY_API) to the B class?

CodePudding user response:

Do I have to add my macro (MY_API) to the B class?

If that B class is also exported/imported (which, presumably, it is), then: Yes, you do.

Try the following code, where we are building the DLL and exporting the classes:

#define BUILD_DLL

#ifdef BUILD_DLL
#define MY_API __declspec(dllexport)
#else
#define MY_API __declspec(dllimport)
#endif

class MY_API A {
public:
    void some_method();

    class B {
    public:
        void other_method();
    };
};

// Dummy definitions of the exported member functions:
void MY_API A::some_method() {}
void MY_API A::B::other_method() {}

Compiling this gives the following error (MSVC, Visual Studio 2019):

error C2375: 'A::B::other_method': redefinition; different linkage

The message disappears, and the code compiles without issue, if we simply add the MY_APP attribute to the nested class:

//...
    class MY_API B { // Add attribute to nested class
    //...
  • Related