I'm not sure why a static
declared variable is not being recognized in my C++ class. I am using _beginthreadex()
, so from what I found, it seems I need the class function containing _beginthreadex()
to be declared as static
.
Here is a working example, compiled with Visual Studio 2019.
The main program main.cpp
simply initializes the class:
#include "CWinSock.h"
CWinSock *clsCWinSock;
INT main(INT argc, char* argv[])
{
clsCWinSock = new CWinSock();
while (1)
;
return 0;
}
Here is the simple class header CWinSock.h
:
#pragma once
#include <Windows.h>
class CWinSock
{
public:
CWinSock();
~CWinSock();
void CreateServer();
static UINT dwServerPort;
private:
static unsigned WINAPI ListenAndAccept(void*);
};
And here is the class .cpp file:
#include <windows.h>
#include <process.h> /* _beginthread, _endthread */
#include "CWinSock.h"
UINT CWinSock::dwServerPort;
CWinSock::CWinSock() {dwServerPort = 61801;}
CWinSock::~CWinSock() {}
static unsigned WINAPI ListenAndAccept(void *)
{
UINT dwPort = CWinSock::dwServerPort;
return 0;
}
void CWinSock::CreateServer()
{
// Call the main example routine.
UINT threadID = 0;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ListenAndAccept, NULL, 0, &threadID);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
This is the basics, yet I get the error: LNK2001, unresolved external symbol "public: static unsigned int CWinSock::dwServerPort" (?dwServerPort@CWinSock@@2IA)
. Putting UINT CWinSock::dwServerPort;
in the .cpp file solves that error.
BUT, it ALSO errors on the function ListenAndAccept
. Even if I declare it in the .cpp file as suggested, it still gives an error.
It doesn't give the error if I take off the static
, but from what I understand (which might be incorrect), _beginthreadex()
won't work without its function being static
? Or I'm doing something really wrong?
Any help in calling _beginthreadex()
from a class and the reason for static
is appreciated also!