2010-05-25 82 views
1

我正在使用vC++(2010)。我正在嘗試爲服務器端套接字創建一個類。這裏是頭文件vC++ - 靜態成員顯示錯誤

#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" ([email protected]@@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

在你的.cpp文件,而不是在你的.h文件中加上:

SOCKET AcceptSocket::s; 

它被包含在許多.cpp文件,如果你在.h文件中都有它。因此,當你鏈接它不知道使用哪一個。

+0

R.Bondy 謝謝你的建議,它的工作 – prabhakaran 2010-05-25 14:31:20

0

也許一個#pragma once在您的頭文件的一開始將解決問題。

錯誤消息告訴你鏈接器找到你的類的多個定義,顯然是因爲你不止一次地包含頭部。

一般來說這很好,但是你應該在你的頭文件中添加一些所謂的inclusion guards來防止這個錯誤。

編輯:

剛纔看到布萊恩R. Bondys的答案是正確的。