Unresolved external symbol static variable (variable used by method defined in header)

前端 未结 3 743
梦如初夏
梦如初夏 2021-01-19 13:07

Here is the .h:

class Logger
{
private:
    static int mTresholdSeverity;

public:
    static __declspec(dllexport) void log(const char* message);
    static         


        
相关标签:
3条回答
  • 2021-01-19 13:31

    The problem is that mThresholdSeverity is not exported from the DLL, but the two accessors are defined inline, so wherever they're called they have to be able to see mThresholdSeverity. There are two solutions: either export mThresholdSeverity from the DLL (sorry, I don't remember how to do that off the top of my head), or make the accessors non-inline functions, define them in the DLL, and export them from the DLL.

    0 讨论(0)
  • 2021-01-19 13:50

    Here is how it works.

    Every DLL (or EXE) or otherwise complete "fully-linked" binary, must have definitions of all referenced names, including static variables, including static data members in C++ classes.

    They will be separate across DLLs in the application. That means, this variable value will be different, depending on which DLL you look from. Moving the functions to CPP file will make them do a different thing: they will now see the DLL's copy of the variable and not the EXE's.

    To make what you wrote compile, there has to be the definition from the CPP present in all user binaries at one place. That means, the DLL and the users of the DLL (EXEs or DLLs) must have one CPP file with this definition.

    This is a very big hassle, because among other things it makes Singleton pattern impossible (having a shared data object for all users within the program) and each copy of a DLL must have its own static state. Such problem exists only on Windows, with DLLs which are dynamic *loaded * libraries. On UNIX systems, there is a different technology known as Shared Objects (SO). They support true dynamic linking, which means, running the linker to resolve external names at runtime.

    0 讨论(0)
  • 2021-01-19 13:51

    Just so this doesn't get lost in the noise: you can change your accessors into ordinary, non-inline functions and define them in the same source file as your static data member. As long as you export them, you'll be able to call them from anywhere, and they'll access the static data just fine.

    0 讨论(0)
提交回复
热议问题