2012-07-27 47 views
2

我有3個文件Test.h,Test.cpp的和main.cpp中命名空間的錯誤而宣告它全球範圍內

Test.h

#ifndef Test_H 
#define Test_H 
namespace v 
{ 
    int g = 9;; 
    } 
class namespce 
{ 
public: 
    namespce(void); 
public: 
    ~namespce(void); 
}; 
#endif 

Test.cpp的

#include "Test.h" 


namespce::namespce(void) 
{ 
} 

namespce::~namespce(void) 
{ 
} 

Main.cpp

#include <iostream> 
using namespace std; 
#include "Test.h" 
//#include "namespce.h" 


int main() 
{ 

    return 0; 

} 

構建它提供了以下錯誤時..

1>namespce.obj : error LNK2005: "int v::g" ([email protected]@@3HA) already defined in main.obj 
1>C:\Users\E543925\Documents\Visual Studio 2005\Projects\viku\Debug\viku.exe : fatal error LNK1169: one or more multiply defined symbols found 

敬請儘快幫助..

回答

2

你有兩個選擇:

靜:

namespace v 
{ 
    static int g = 9; //different copy of g per translation unit 
} 

的extern:

namespace v 
{ 
    extern int g; //share g between units 
} 

// add initialization to .cpp: 
namespace v { int g = 9; } 
+0

謝謝.. 得到了解決方案.. – Kenta 2012-07-27 11:15:52

5

這是一個定義:

namespace v 
{ 
    int g = 9; 
} 

是獲取main.obj複製並且由於.cpp文件中的每個文件中的#include "Test.h"而導致test.obj。包含後衛#ifndef Test_H只能防止單個翻譯單元中的多個包含物。

更改爲:

namespace v 
{ 
    extern int g; // This is now a declaration and extern tells the compiler 
        // that there is definition for g somewhere else. 
} 

,並添加以下到Test.cpp

namespace v 
{ 
    int g = 9; // This is now the ONLY definition of 'g', in test.obj. 
} 
+0

明白了..謝謝你的回覆.. – Kenta 2012-07-27 11:15:10

3

你想要的g只是一個實例被大家訪問? 在標題中使用

extern int g; // declaration 
在Test.cpp的

,把

int v::g = 9; //definition