2013-04-07 36 views
0

內全局變量我定義變量 'a' 在header.h,並用它在test1.cpp測試2.cpp。 當我蓋了,我得到了像C++ - 多個文件

致命錯誤LNK1169鏈接錯誤:一個或多個多重定義符號找到

什麼問題? 我想用全局變量'a'可以用在多個cpp中。

header.h

的main.cpp

#include "header.h" 
#include "test1.h" 
#include "test2.h" 

using namespace std; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    test1(); // expected output : 0 
    test1(); // expected output : 1 
    test2(); // expected output : 2 
    test2(); // expected output : 3 

    cout << "in main : " << a << endl; // expected output : 3 

    return 0; 
} 

test1.h

extern int a; 

void test1(); 

test1.cpp

#include "test1.h" 
#include "header.h" 

void test1() { 
    cout << "test1 : " << a << endl; 
    a++; 
} 

test2.h

extern int a; 

void test2(); 

測試2.cpp

#include "test2.h" 
#include "header.h" 

void test2() { 
    cout << "test2 : " << a << endl; 
    a++; 
} 
+0

發佈編譯器選項日誌。 – devnull 2013-04-07 09:41:11

回答

5

你應該只把extern申報一個頭文件。這個頭文件應該被任何其他想要使用的文件包含在a中。

然後你應該把定義int a = 0;放在一個執行文件(一個.cpp文件)。

此刻,您在多個頭文件中有很多extern聲明,這是好吧但只是令人困惑。你應該簡單地在一個地方聲明它。但是,您遇到的主要問題是您在定義aheader.h。如果將該標題包含在多個翻譯單元中,則會有多個定義。

+0

最好用適當的功能參數傳輸完全替換這個全局。 – SChepurin 2013-04-07 09:48:50

+0

我想讓test1和test2互相不認識。 – chris 2013-04-07 10:01:03

+0

@ user1285975如果你不想讓這些模塊相互認識,你的架構在邏輯上是不正確的。在這種情況下,必須將聲明和定義放入新的第三個模塊中,test1和test2都知道這個模塊。 – dialer 2013-04-07 10:09:44