命名空间错误,而在全局范围中声明它 [英] Namespace error while declare it in global scope

查看:196
本文介绍了命名空间错误,而在全局范围中声明它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个文件Test.h,Test.cpp和main.cpp

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 b
$ b

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

尽快帮助。

推荐答案

您有两个选项:

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

这篇关于命名空间错误,而在全局范围中声明它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆