![](/img/trans.png)
[英]Why does an overflow in a static variable cause seg fault but not global variables?
[英]Why does global variables in a header file cause link error?
我總是得到以下錯誤,即使我已將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
}
但是,如果我從頭文件中刪除了全局變量,這些代碼就會成功編譯。
我不明白為什么。 有人能解釋為什么嗎? 先感謝您。
線條像
const char *Bittorrent = "BitTorrent protocol";
const char eight_byte[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
無論代碼是在頭文件中還是在a .c中直接定義全局變量( #include
只是文本插入標題的內容)。 相反,您應該在exaclty一個源文件中定義並更改標頭以提供extern
聲明:
extern const char *Bittorrent;
extern const char *eight_byte;
然后可以編譯使用thes變量的所有源代碼,但鏈接器只將變量賦值一次。
因為您在頭文件中定義變量。 然后,包含頭文件的所有源文件都將定義這些變量。
您可以使用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
。
標題:
extern const char *Bittorrent;
Main(在main函數之前/作為gloabal變量):
const char *Bittorrent = "BitTorrent protocol";
這樣你的標題告訴每個文件都有名為“Bittorrent”的變量,但只有你的main.c文件中有真正創建它的部分。
通過初始化變量,您可以在包含文件的每個位置定義它。 假設這些模塊鏈接在一起,您現在有多個定義,這是一個錯誤。
您可以使用extern標記在標頭中聲明變量,然后在其中一個.c模塊中初始化它。
在你的.h文件中:
extern int i;
在你的一個.c文件中:
int i = 1;
然而,
還要注意你有一個錯字。
Send_fisrt_Handshake
而不是Send_first_Handshake
。
我可以想象你只是把它誤輸入了你的問題。 但你永遠不知道; 在大型代碼中很難找到並修復拼寫錯誤。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.