M C Roberts

To keep this problem simple I'm building a new project for an SDI using MFC in a shared dll and I create a new class:

CThreadTest : public CWinThread

{

<snip>

public:

static CRITICAL_SECTION m_csCritTest;

}

In my CCritTestApp class I have:

#include "ThreadTest.h"

<snip>

BOOL CCritTestApp::InitInstance()

{

<snip>

InitializeCriticalSection(&CThreadTest::m_csCritTest);

}

int CCritTestApp::ExitInstance()

{

DeleteCriticalSection(&CThreadTest::m_csCritTest);

}

That's it, compiling it I'm getting a LNK2001 error

Error 1 error LNK2001: unresolved external symbol "public: static struct _RTL_CRITICAL_SECTION CThreadTest::m_csCritTest" ( m_csCritTest@CThreadTest@@2U_RTL_CRITICAL_SECTION@@A) CritTest.obj

From the help files on LNK2001:

Trying to use a variable declared within a function (a local variable) outside the scope of that function can cause LNK2001.

my stdafx.h is standard, but I have tried adding <winbase.h> and <afxmt.h> in various places/order.

my compiler options are all default.

What do I need to do in VS2005 C++ The CThreadTest::m_csCritTest should be globally visible to the CCritTestApp.

I have gotten this to work and the same problem use to show up under VS6 C++ but I can't remember what I've done to get this to work correctly. I think that I do not need to resort to defining the critical section outside of the class, maybe I do need to do this...

Thanks in adv!



Re: Visual C++ General VS2005 VC++ MFC build Lnk2001 error

_johnr_

Hi M,

For static members you also need to define the variable outside of the class declaration (along with the rest of your class's code). E.g;

Code Snippet

CThreadTest : public CWinThread
{
<snip>
public:
static CRITICAL_SECTION m_csCritTest;
}

Then in crittest.cpp:

CRITICAL_SECTION CThreadTest::m_csCritTest;

John.





Re: Visual C++ General VS2005 VC++ MFC build Lnk2001 error

Marius Bancila

To clarify a little: static data members are not part of the object (they don't have class scope). Their declaration is not considered a definition (like in the case of non-static data members). Thus, the static data members are declared in class scope, but the definition is performed in file scope and they have external linkage.

You code only contains the declaration (in class scope). What is missing is the definition (in file scope) and hence the error.






Re: Visual C++ General VS2005 VC++ MFC build Lnk2001 error

M C Roberts

Thanks, that was it. I found putting it at the top of the same class' cpp file seemes to work best.



Re: Visual C++ General VS2005 VC++ MFC build Lnk2001 error

Marius Bancila

Well, you can put it in the header, only if the header is included in a single source file. Otherwise, you get LNK2005 error:

foo1.obj : error LNK2005: "public: static int foo:Big Smileata" ( data@foo@@2HA) already defined in win32test.obj

foo2.obj : error LNK2005: "public: static int foo:Big Smileata" ( data@foo@@2HA) already defined in win32test.obj