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

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

问题描述

我有一个命名空间 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就不能工作?staticnamespace 中使用时是什么意思?

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天全站免登陆