2014-12-30 110 views
0

我在這裏搜索過,發現這個問題的次數很多,但作者通常沒有提供代碼示例,我今天遇到了這個問題,我不太清楚如何解決這個問題。Linker LNK2005錯誤

1個錯誤列表bool Init([email protected]@A_NA) already defined in Client.obj。這裏是我的Client.cpp,Main.cpp和Main.h的部分代碼。

Client.cpp

#include "stdafx.h" 
#include "Main.h" 
// the rest of the code doesn't have anything to do with this error.. 

Main.h

#include "stdafx.h" 
bool Init; 
// the rest of the code doesn't have anything to do with this error.. 

Main.cpp的

#include "stdafx.h" 
#include "Main.h" 

int main() 
{ 
    Init = false; 
    return 0; 
} 

回答

2

#include "Main.h"您已經定義bool Init;,所以每一次你有Main.h,你將重新定義Init。如果您Init靜態,

static bool Init; 

這裏Init將網頁級別範圍,你的代碼應該正常工作。

或者更好,您在Math.hInit的extern,

extern bool Init; 

然後在.cpp文件中定義它,這樣你將有多個聲明,但一個定義。

+0

如果您必須使用全局變量,則最好在頭文件中顯示並在一個cpp文件中定義。 –

+0

@RetiredNinja儘管如此,它會干擾其他全局'Init',你的方法一般是正確的,但是OP有客戶端庫,它已經定義了'Init'。 –

+0

我沒有看到他在使用圖書館。他顯然有兩個cpp文件和一個標題中聲明的變量,導致多重定義錯誤。如果您將其設爲靜態,則錯誤將消失,但每個cpp文件將具有不同的變量。如果你外部並在一個地方定義它,那麼它們共享相同的變量。 –