Linking problems with storage class defined as sta

2019-09-03 03:13发布

On the .dll file

//SWC.h

#ifndef _SWC_
#    define _SWC_
#    define SWC_CALL __declspec(dllexport)
#else
#    define SWC_CALL __declspec(dllimport)
#endif

namespace SWC
{

    struct SWC_CALL Mouse
    {
        //interface
    };

    class SWC_CALL SWC_Base : public someClass1, public someClass2
    {

        static Mouse mouse;

    };

    //other classes goes here...
}

//SWC_Base.cpp
namespace SWC
{

    Mouse SWC_Base::mouse; //needed, to compile

    //other SWC_Base function definition

}

On .exe file

with the static struct Mouse mouse I defined on the SWC_Base I get linking errors

I solve my problem by redefining it again on this file

//main.cpp

#include "SWC.h"

#pragma comment (lib, "..\\SWC")

SWC::Mouse SWC::SWC_Base::mouse; //<- why do I need to redefine it again?

int main()
{
    //...

    return 0;

}

I already define the SWC_Base::mouse on its .cpp file, why do I need to redefine it again on the file who uses it? I know I can have this more problems as my .dll project is growing with static variables on it.

2条回答
乱世女痞
2楼-- · 2019-09-03 04:05

You have added an anymous namespace { } around your definition (in case that you posted the real code) in the header file. Each anonymous namespace will translated to a compilation unit specific namespace by the compiler. Therefore you get always a new class in a new namespace.

To solve the problem you can either

  • move the declaration, the defination, and all use to one source file
  • use a named namespace
查看更多
Viruses.
3楼-- · 2019-09-03 04:06

If your calling code will use __declspec (dllimport) this trouble will be gone :)

#ifdef EXPORTING_SWC
  #define SWC_CALL __declspec(dllexport)
#else
  #define SWC_CALL __declspec(dllimport)
#endif
查看更多
登录 后发表回答