名称空间未定义或重新定义,为什么?

namespace either undefined or redefined, why?

本文关键字:定义 为什么 新定义 空间 未定义      更新时间:2023-10-16

只是一个非常小的程序来测试如何使用名称空间。我将其分成3个文件,因为在大型产品中,ns.h是名称空间接口,ns.cpp是实现。我没法把这些东西都放到一个文件里。

代码如下:

//ns.h
#ifndef MY_H
#define MY_H
namespace my
{
    int a=1;
    int b=0;
    void test();
}
#endif
//ns.cpp
#include <iostream>
#include "ns.h"
using namespace my;
//my::a=1;
//my::b=0;
void my::test()
{
    std::cout<<a<<std::endl;
}
//testns.cpp
#include <iostream>
#include "ns.h"
int main()
{
    std::cout<<my::b<<std::endl;
    my::test();
}

如果我保留上面的代码,编译将得到:

testns.obj : error LNK2005: "int my::b" (?b@my@@3HA) already defined in ns.obj
testns.obj : error LNK2005: "int my::a" (?a@my@@3HA) already defined in ns.obj

如果我注释语句#include "ns.h",我将得到undefined错误。

D:mfctestns.cpp(5) : error C2653: 'my' : is not a class or namespace name
D:mfctestns.cpp(5) : error C2065: 'b' : undeclared identifier
D:mfctestns.cpp(6) : error C2653: 'my' : is not a class or namespace name
D:mfctestns.cpp(6) : error C2065: 'test' : undeclared identifier
如果你知道怎么做,请帮助我。非常感谢。

头文件用于声明,而不是定义。这与名称空间的问题无关。

//ns.h
#ifndef MY_H
#define MY_H
namespace my
{
    extern int a, b; // declared, not defined thanks to 'extern'.
    void test();
}
#endif
//ns.cpp
#include <iostream>
#include "ns.h"
int my::a=1; // now we provide the actual definitions.
int my::b=0;
void my::test()
{
    std::cout << my::a << std::endl;
}
//testns.cpp
#include <iostream>
#include "ns.h"
int main()
{
    std::cout << my::b << std::endl;
    my::test();
}

ns.h中定义了两个变量ab,然后头文件被包含在两个源文件中。这违反了一个定义规则,因为变量现在是在包含ns.h的两个翻译单元中定义的。

你需要做的是在头文件中声明变量,并在单个源文件中定义它们。

要解决这个问题,将ns.h更改为

#ifndef MY_H
#define MY_H
namespace my
{
    extern int a;
    extern int b;
    void test();
}
#endif
在<<p> em> ns.cpp
#include <iostream>
#include "ns.h"
using namespace my;
int my::a=1;
int my::b=0;
void my::test()
{
    std::cout<<a<<std::endl;
}

在头文件中定义变量不是标准做法;它们被重新定义,每次你#include头,导致你所看到的链接错误。

如果您需要在源文件之间共享变量(并且很少有这样做的好理由),那么您应该在头文件中将声明为extern,然后在您的一个源文件中定义它们。

相关文章: