Namespace error while declare it in global scope

旧街凉风 提交于 2019-12-12 16:43:59

问题


I have 3 files Test.h , Test.cpp and 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;

}

during building it gives the following error ..

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

kindly help as soon as possible ..


回答1:


You have two options:

static:

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; }



回答2:


This is a definition:

namespace v
{
    int g = 9;
}

that gets duplicated in main.obj and test.obj due to the #include "Test.h" in each of the .cpp files. The include guard #ifndef Test_H only prevents multiple inclusions in a single translation unit.

Change to:

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

and add the following to the Test.cpp:

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



回答3:


You want just one instance of g accessed by everyone? In the header, use

extern int g; // declaration

in Test.cpp, put

int v::g = 9; //definition


来源:https://stackoverflow.com/questions/11686508/namespace-error-while-declare-it-in-global-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!