命名空间中的静态变量和非静态变量 [英] static vs non-static variables in namespace

查看:132
本文介绍了命名空间中的静态变量和非静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命名空间 foo ,它包含一个整数 bar ,声明为...

I have a namespace foo which contains an integer bar, declared so...

foo.h:

namespace foo {
    int bar;
}

现在如果我包括 foo.h 只有一个文件,这工作很好。但是当我从两个或多个文件中包含 foo.h 时会出现问题:我得到一个链接器错误。我想,如果我声明 bar static ,我可以包括 foo.h 在多个文件中。这对我来说看起来很奇怪,因为我不知道可以在命名空间中声明一个静态变量。 (这是什么意思?)

Now if I include foo.h in only one file, this works just fine. But a problem arises when I include foo.h from two or more files: I get a linker error. I figured out that if I declare bar as static, I can include foo.h in more than one file. This seems strange to me, because I wasn't aware that one could declare a static variable inside of a namespace. (what does that even mean?)

为什么这样工作?更重要的是,为什么无效 static 命名空间中使用时, static 是什么意思?

Why does this work? And more importantly, why doesn't it work without static? What does static mean when used in a namespace?

推荐答案

static 在不同的上下文中有多种含义。在这个特定的上下文中,它意味着变量具有内部链接,因此包括该头部的每个翻译单元将具有它自己的变量副本。

There are multiple meanings for static in different contexts. In this particular context it means that the variable has internal linkage, and thus each translation unit that includes that header will have it's own copy of the variable.

将静默链接器错误,它将这样做为每个生成的对象文件维护一个单独的 foo :: bar 变量(更改将不会在不同的对象文件中可见) 。

Note that while this will silent the linker error, it will do so maintaining a separate foo::bar variable for each one of the object files generated (changes will not be visible across different object files).

如果你想要一个变量,你应该在头中声明为 extern 在一个翻译单位。

If you want a single variable, you should declare it as extern in the header and provide a single definition in one translation unit.

这篇关于命名空间中的静态变量和非静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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