I got a link error when I tried to access vector outside my thread. My design is, when I get a message from a client, I want the massage or data to be in my data queue for further operation. But I can't get them work. Here is my codes:
.cpp file:
// Inside the recv thread
start:
err = recvfrom(RecvSocket, lpData->RecvBuf, BufLen, 0, (SOCKADDR *)&lpData->SenderAddr, &SenderAddrSize);
//lpData is used to access Recv Structure which stores the attributes of the server and client.
switch(lpData->port)
{
case 6516:
{
BuffStack1.push_back(lpData->RecvBuf);
break;
}
case 6517:
{
break;
}
case 6518:
{
break;
}
}
goto start;
.h file:
class CUdpSocket
{
public:
CUdpSocket(void);
~CUdpSocket(void);
void ServerRecv(int port);
void ClientSend(const char *ip, int port, const char *buff);
unsigned static __stdcall ServerRecvThread(void *arguments);
unsigned static __stdcall ClientSendThread(void *arguments);
CString static Itoa(int data);
void Mix();
private:
RecvStruct *pRecvData;
SendStruct *pSendData;
vector<HANDLE>threadStl;
static vector<char*>BuffStack1; // 开发者_开发百科Here is my stack vector
static vector<char*>BuffStack2;
static vector<char*>BuffStack3;
HANDLE hThread;
unsigned threadID;
static BufferData *ptrBufferData;
};
I am a bit confused whether I need to put static or not. And when I put static, the error will be:
error LNK2001: unresolved external symbol "private: static class std::vector<char *,class std::allocator<char *> > CUdpSocket::BuffStack1" (?BuffStack1@CUdpSocket@@0V?$vector@PADV?$allocator@PAD@std@@@std@@A)
And if I didn't put static statement, the error says:
error C2228: left of '.push_back' must have class/struct/union
Please help.
Thank you.
I think that the problem is that in C++, using static
data members in a class is a two-step process. First, you need to declare the static
variable, indicating that it has a name and type, and then you must define the static
variable to give it storage space in one of the translation units. My guess is that you have done that first step but not the second.
To define a static
variable, put a definition like this one into the .cpp file:
vector<char*> CUdpSocket::BuffStack1;
Note that you do not repeat the static
keyword here. Instead, you just give the type and fully-qualified name of the static
data member. If you want to use a non-default constructor for the static
data member, you can do so here as well.
Hope this helps!
PS. Please don't use labels and goto
s to implement your loop... use a while(true)
loop instead! :-)
EDIT: If you're going to be accessing these vector
s from the thread, make sure you have some appropriate synchronization in place. It is not safe to read and write a vector
from multiple threads without ensuring at the most one thread can modify it at any one time.
精彩评论