C++ 如何在名称空间中用“定义”来定义变量;使用名称空间";?

C++ 如何在名称空间中用“定义”来定义变量;使用名称空间";?,c++,C++,因此,我有一个名称空间thing,在头中声明了extern int变量。我试图用使用名称空间东西在.cpp中定义它们简化了初始化,但它似乎不像我在thing.cpp中定义变量时所期望的那样工作。有什么好处 main.cpp: #include <cstdio> #include "thing.hpp" int main() { printf("%d\n%d\n",thing::a,thing::func()); printf(

因此,我有一个名称空间
thing
,在头中声明了
extern int
变量。我试图用
使用名称空间东西在.cpp中定义它们
简化了初始化,但它似乎不像我在
thing.cpp
中定义变量时所期望的那样工作。有什么好处

main.cpp:

#include <cstdio>
#include "thing.hpp"

int main()
{
    printf("%d\n%d\n",thing::a,thing::func());
    printf("Zero initialized array:\n");
    for(int i = 0; i < 10; i++)
        printf("%d",thing::array[i]);

    return 0;
}
thing.cpp

#include "thing.hpp"

using namespace thing;

// I wanted to do the same thing with 'a' for all variables
int a,thing::b,thing::array[10];

int thing::func() {
    return 12345;
}
错误:

/tmp/ccLbeQXP.o: In function `main':
main.cpp:(.text+0x11): undefined reference to `thing::a'
collect2: error: ld returned 1 exit status

使用命名空间thing
允许您使用
thing
命名空间中的标识符,而无需使用
thing::
作为前缀。它有效地将它们拉入
using
指令所在的名称空间(或全局名称空间)


它不会在名称空间
中进一步定义thing
。所以当你定义
inta,它只是在全局名称空间中。您需要使用
int thing::a
名称空间thing{int a;}
在名称空间中定义它。

是否编译thing.cpp并将其链接到最终程序?@πάνταῥεῖ 是的,当我使用
thing::a
而不仅仅是
a
时,代码工作正常。当然,你必须完全限定你的符号名,除非你使用thing::a语句。@πάνταῥεῖ 那么是什么规则使得我不能使用
使用名称空间的东西呢?如果我在头中包含
iostream
,在.cpp中包含
使用名称空间std
,我可以使用它的函数/方法,而不使用
std
名称空间前缀,那么为什么不将
thing.cpp
的内容包装在
名称空间thing{…}/code>中,就像您使用
thing.hpp
一样?太好了,我已经更改了问题标题,以匹配我所寻找的答案。
/tmp/ccLbeQXP.o: In function `main':
main.cpp:(.text+0x11): undefined reference to `thing::a'
collect2: error: ld returned 1 exit status