【问题标题】:Namespace error while declare it in global scope在全局范围内声明命名空间错误
【发布时间】:2012-07-27 11:04:35
【问题描述】:

我有 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" (?g@v@@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

请尽快提供帮助..

【问题讨论】:

    标签: c++ multiple-definition-error


    【解决方案1】:

    这是一个定义:

    namespace v
    {
        int g = 9;
    }
    

    由于每个.cpp 文件中的#include "Test.h",它在main.objtest.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.
    }
    

    【讨论】:

      【解决方案2】:

      您只希望每个人都可以访问一个g 实例吗? 在标题中,使用

      extern int g; // declaration
      

      在Test.cpp中,放入

      int v::g = 9; //definition
      

      【讨论】:

        【解决方案3】:

        你有两个选择:

        静态:

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

        外部:

        namespace v
        {
            extern int g; //share g between units
        }
        
        // add initialization to .cpp:
        namespace v { int g = 9; }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-16
          相关资源
          最近更新 更多