vc ++ - 静态成员显示错误

时间:2010-05-25 13:35:15

标签: visual-c++ static-members

我正在使用vc ++(2010)。我正在尝试为服务器端套接字创建一个类。这是头文件

#include<winsock.h>
#include<string>
#include<iostream>

using namespace std;

class AcceptSocket
{
//  static SOCKET s;    
protected:

SOCKET acceptSocket;
public:
AcceptSocket(){};
void setSocket(SOCKET socket);
static void EstablishConnection(int portNo,string&);
static void closeConnection();
static void StartAccepting();
virtual void threadDeal(); 
static DWORD WINAPI MyThreadFunction(LPVOID lpParam);
};

SOCKET AcceptSocket::s;

和相应的源文件

#include<NetWorking.h>
#include<string>

void AcceptSocket::setSocket(SOCKET s)
{
acceptSocket=s;
}

void AcceptSocket::EstablishConnection(int portno,string &failure)
{
WSAData w;
int error = WSAStartup(0x0202,&w);

if(error)
    failure=failure+"\nWSAStartupFailure";

if(w.wVersion != 0x0202)
{
    WSACleanup();
    failure=failure+"\nVersion is different";
}

SOCKADDR_IN addr;

addr.sin_family=AF_INET;

addr.sin_port=htons(portno);

addr.sin_addr.s_addr=htonl(INADDR_ANY);

AcceptSocket::s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);


if(AcceptSocket::s == INVALID_SOCKET)
    failure=failure+"\nsocket creating error";

if(bind(AcceptSocket::s,(LPSOCKADDR) &addr,sizeof(addr)) == SOCKET_ERROR)
    failure=failure+"\nbinding error";

listen(AcceptSocket::s,SOMAXCONN);

}


void AcceptSocket::closeConnection()
{
if(AcceptSocket::s)
    closesocket(AcceptSocket::s);


WSACleanup();
}

void AcceptSocket::StartAccepting()
{
sockaddr_in addrNew;
int size=sizeof(addrNew);
while(1)
{
    SOCKET temp=accept(AcceptSocket::s,(sockaddr *)&addrNew,&size);
    AcceptSocket * tempAcceptSocket=new AcceptSocket();
    tempAcceptSocket->setSocket(temp);
    DWORD threadId;
    HANDLE thread=CreateThread(NULL,0,MyThreadFunction,(LPVOID)tempAcceptSocket,0,&threadId);
}
}

DWORD WINAPI AcceptSocket::MyThreadFunction(LPVOID lpParam)
{
AcceptSocket * acceptsocket=(AcceptSocket *) lpParam;
acceptsocket->threadDeal();
return 1;
}

void AcceptSocket::threadDeal()
{
"You didn't define threadDeal in the derived class";
}

现在main.cpp是

#include<Networking.h>

int main()
{
}

当我编译错误时,我得到了

Error   1   error LNK2005: "private: static unsigned int AcceptSocket::s" (?s@AcceptSocket@@0IA) already defined in NetWorking.obj  C:\Documents and Settings\prabhakaran\Desktop\check\check\main.obj  check

Error   2   error LNK1169: one or more multiply defined symbols found   C:\Documents and Settings\prabhakaran\Desktop\check\Debug\check.exe 1   1   check

可能导致此问题的原因以及如何解决?

3 个答案:

答案 0 :(得分:3)

将它放在.cpp文件而不是.h文件中:

SOCKET AcceptSocket::s;

如果您的.h文件中包含它,它将被包含在许多.cpp文件中。因此,当您链接时,它不知道使用哪一个。

答案 1 :(得分:0)

在您的头文件的最开头可能会有#pragma once来解决问题。

错误消息告诉您链接器找到了您的类的多个定义,显然是因为您多次包含标题。

一般来说这很好,但是你应该总是在头文件中添加一些所谓的inclusion guards来防止这个错误。

编辑:

刚才看到Brian R. Bondys的回答是正确的。

答案 2 :(得分:0)

我想详细说明弗兰克所说的话。这是一个常见的假设,包括警卫可能会解决这些错误。由于解释有点冗长,我已经发了一篇关于它的博客文章来解释细节: http://daniel-albuschat.blogspot.com/2010/08/what-include-guards-in-c-are-and-what.html 希望这很有用。