2013-07-11 32 views
1

我總是得到以下錯誤,即使我已經把頭文件中的include guard。爲什麼頭文件中的全局變量會導致鏈接錯誤?

duplicate symbol _Bittorrent in: 
    /Users/tracking/Library/Developer/Xcode/DerivedData/SHT-giuwkwyqonghabcqbvbwpucmavvg/Build/Intermediates/SHT.build/Debug/SHT.build/Objects-normal/x86_64/main.o 
    /Users/tracking/Library/Developer/Xcode/DerivedData/SHT-giuwkwyqonghabcqbvbwpucmavvg/Build/Intermediates/SHT.build/Debug/SHT.build/Objects-normal/x86_64/Handshake.o 
duplicate symbol _eight_byte in: 
    /Users/tracking/Library/Developer/Xcode/DerivedData/SHT-giuwkwyqonghabcqbvbwpucmavvg/Build/Intermediates/SHT.build/Debug/SHT.build/Objects-normal/x86_64/main.o 
    /Users/tracking/Library/Developer/Xcode/DerivedData/SHT-giuwkwyqonghabcqbvbwpucmavvg/Build/Intermediates/SHT.build/Debug/SHT.build/Objects-normal/x86_64/Handshake.o 
ld: 2 duplicate symbols for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

下面是.H頭文件,.c文件,和main.c中

的main.c

#include "Handshake.h" 
int main(int argc, char** argv) 
{ 
    // some code. 
    return 0; 
} 

Handshake.h

#ifndef SHT_Handshake_h 
#define SHT_Handshake_h 

const char *Bittorrent  = "BitTorrent protocol"; 
const char eight_byte[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 

#endif 

Handshake.c

#include "Handshake.h" 


int Send_fisrt_Handshake(download_connection *pPeer, Handshake *necessary_info) 
{ 
    //some statements 
    return 1; 
} 

void Set_Handshake_information(TorrentFile* pArg, Handshake *pYours) 
{ 

    //some statements 

} 

但是,如果我從頭文件中刪除全局變量,這些代碼將成功編譯。
我不明白爲什麼。有人能解釋爲什麼嗎?先謝謝你。

+0

不要將全局變量定義放在頭文件中。只在其中放置聲明。 – johnchen902

回答

5

線,如

const char *Bittorrent  = "BitTorrent protocol"; 
const char eight_byte[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 

定義論文全局變量,無論如果代碼是在頭文件或INE直接在.C(#include是標題的內容只是文本插入)。 相反,你應該在exaclty一個源文件中的定義和改變標題,以提供一個extern聲明代替:

extern const char *Bittorrent; 
extern const char *eight_byte; 

然後使用THES變量所有的源可以被編譯,但是鏈接器將變量只有一次。

1

頁眉:

extern const char *Bittorrent; 

主(前的主要功能/作爲gloabal變量):

const char *Bittorrent  = "BitTorrent protocol"; 

這樣,你的頭告訴每個文件有變量命名爲 「BT下載」,但只你的main.c文件中包含真正創建的部分。

1

因爲你定義了頭文件中的變量。然後所有包含頭文件的源文件都會定義這些變量。

可以聲明變量,使用extern關鍵字:

extern const char *Bittorrent; 
extern const char eight_byte[8]; 

然後在一個源文件中定義的變量。

或者你可以定義變量如static,這限制了它們的範圍到翻譯單元(即源文件):

static const char *Bittorrent  = "BitTorrent protocol"; 
static const char eight_byte[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 

這是C++,其中const也意味着static不同。

1

通過初始化變量,您可以在包含該文件的每個位置定義它。假設這些模塊連接在一起,現在您有多個定義,這是一個錯誤。

可以用extern標記聲明頭中的變量,然後在您的.c模塊之一中初始化它。

在您的.h文件中:

extern int i; 

在你的.c文件之一:

int i = 1; 

然而,

1

另外請注意,你有一個錯字。

Send_fisrt_Handshake而不是Send_first_Handshake

我可以想象,你只是誤輸入你的問題。但你永遠不知道;拼寫錯誤很難找到並修復大型代碼。 :)

相關問題