2012-04-13 90 views
3

我試圖使用從分離.cpp文件的全局變量我有一個init.h裏文件:LNK2005:「已經定義的錯誤

//init.h 
#ifndef init 
#define init 
int a = 3; 
#endif 

我有一個init.cpp文件: //init.cpp #include init.h

於是最後我的main.cpp文件是:

//main.cpp 
#include "init.h" 
int main(void) 
{ 
    while(1) 
    { 
    } 
} 

在此之後,我得到的錯誤:

1>init.obj : error LNK2005: "int a" ([email protected]@3HA) already defined in main.obj 
1> ..deneme.exe : fatal error LNK1169: one or more multiply defined symbols found 

爲什麼我的#infdef控件不能解決這個問題?我也嘗試使用#pragma once,但我得到了同樣的錯誤。我的代碼有什麼問題?

回答

9

您需要將變量標記爲extern,並在實現文件中僅定義一次。

由於代碼是現在,你打破了一個定義規則。在這種情況下,包含守衛不起作用,因爲包含該頭文件的所有翻譯單元都會重新定義變量。

你真正需要:

//init.h 
#ifndef init 
#define init 
extern int a; 
#endif 

和定義:

//init.cpp 
#include "init.h" 
int a = 3; 

此外,三思使用全局之前。你究竟在努力實現什麼?

+0

好吧,我忘了寫包含init.h文件的init.cpp文件。當我使用extern時問題仍然存在。 – 2012-04-13 12:44:45

+1

@volkansezer不可能是正確的。你確定你沒有忘記從標題中刪除= 3嗎?你確定你在頭文件中聲明它爲extern而不是實現文件嗎? – 2012-04-13 13:02:57

+0

是的,你是對的,我已經改變了你的建議和問題解決,非常感謝。再次感謝我從不同的源文件實現同樣的全局變量對我來說非常重要。 – 2012-04-13 23:37:09

相關問題