Search code examples
c++mfccompilationdebug-build

Why RUMTIME_CLASS passed compile without "DECLARE_DYNAMIC" in VS2008 Debug version?


Answered at the bottom. Thanks!

The compiler caught error C2039 and C2065 correctly in Release version;

I'm just curious why the same code CAN pass compile in Debug version?

Is it a known Microsoft bug?

I know DECLARE_DYNAMIC/IMPLEMENT_DYNAMIC will solve the issue. However, without them, why Microsoft passed compile in my debug version? This is the question.


Known the reason. Michael's answer is exactly correct. _AFXDLL is only defined on my Debug configuration. So on Debug version it is using CObject::GetThisClass when expand the macro RUNTIME_CLASS.

So following code will be caught compiler error for both Release and Debug version if DECLARE_DYNAMIC/IMPLEMENT_DYNAMIC were not declared:

CRuntimeClass* p = (CRuntimeClass*) (&XXX::classXXX);

But following code will only fail if _AFXDLL is not pre-defined.

p->IsKindOf(RUNTIME_CLASS(XXX))

Thanks


Solution

  • A likely explanation is that your debug project configuration is linking to the MFC DLL runtime while your release configuration is linking to the static MFC runtime. When building against the MFC DLL the CObject base object definition in afx.h has the following lines enabled due to the _AFXDLL macro being defined (which indicates that the MFC DLL is being used):

    #ifdef _AFXDLL
        static CRuntimeClass* PASCAL _GetBaseClass();
        static CRuntimeClass* PASCAL GetThisClass();
    #endif
    

    So, when _AFXDLL is defined, all objects derived from CObject get a static GetThisClass() function, which is what RUNTIME_CLASS() ends up calling if there isn't a better match introduced by a DECLARE_DYNAMIC().

    If _AFXDLL is not defined, the GetThisClass() function is not declared in CObject - to get one for the class you must use the DECLARE_DYNAMIC() macro and use IMPLEMENT_DYNAMIC() to get a definition.

    So the difference probably isn't a debug vs release, it's a MFC DLL vs MFC static runtime difference.