2012-07-27 85 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