Namespace error while declare it in global scope

2019-07-13 11:37发布

问题:

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