名称空间未定义或重新定义,为什么?
namespace either undefined or redefined, why?
只是一个非常小的程序来测试如何使用名称空间。我将其分成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中定义了两个变量a
和b
,然后头文件被包含在两个源文件中。这违反了一个定义规则,因为变量现在是在包含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
,然后在您的一个源文件中定义它们。
相关文章:
- 为什么在定义函数之前先声明它
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 如果我重新定义 sqrt 函数,为什么使用 std::sqrt 失败?
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 为什么我会收到警告,指出函数已使用但未定义,以及已定义但未使用?
- 模板推导:为什么函数指针模板定义在常量和/或引用时不匹配?
- 为什么转换函数声明不需要至少一个定义类型说明符
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 为什么我会收到链接器错误:未定义对 ..?
- 为什么要将函数声明和定义放在单独的文件中
- 为什么 setjmp/longjmp 的这种用法是未定义的行为?
- 为什么我在 Windows API 中得到对 TextOut() 函数的未定义引用?
- 为什么累积C++定义了两个模板
- 多重定义 - 为什么我不能在标题中定义它们
- c++位域结构体大小定义(为什么它被包装得更大?)