C/C++全局与静态全局
Possible Duplicate:
Static vs global
I'm confused about the differences between global and static global variables. If static means that this variable is global only for the same file then why in two different files same name cause a name collisions?
Can someone explain this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您创建可供链接器在其他文件中使用的
.o
文件时,全局变量(不是static
)就在那里。因此,如果您有两个这样的文件,则会在a
上发生名称冲突:ac:
bc:
因为链接器不知道要使用哪个全局
a
。但是,当您定义静态全局变量时,您是在告诉编译器仅为该文件保留变量,并且不要让链接器知道它。因此,如果您将
static
(在a
的定义中)添加到我编写的两个示例代码中,您将不会发生名称冲突,因为链接器甚至不知道这两个文件中都有一个a
:ac:
bc:
这意味着每个文件都使用自己的
a
,而不知道其他文件。附带说明一下,只要它们位于不同的文件中,就可以将其中一个设为静态,而另一个则不然。如果两个声明位于同一文件中(读取翻译单元),一个
static
和一个extern
,请参阅 这个答案。Global variables (not
static
) are there when you create the.o
file available to the linker for use in other files. Therefore, if you have two files like this, you get name collision ona
:a.c:
b.c:
because the linker doesn't know which of the global
a
s to use.However, when you define static globals, you are telling the compiler to keep the variable only for that file and don't let the linker know about it. So if you add
static
(in the definition ofa
) to the two sample codes I wrote, you won't get name collisions simply because the linker doesn't even know there is ana
in either of the files:a.c:
b.c:
This means that each file works with its own
a
without knowing about the other ones.As a side note, it's ok to have one of them
static
and the other not as long as they are in different files. If two declarations are in the same file (read translation unit), onestatic
and oneextern
, see this answer.每个文件中的静态名称不应导致名称冲突。如果您看到了这一点,请发布(简短的)演示代码来显示它,以及您正在使用的确切编译器,以便我们可以正确验证代码并假设它是正确的,适当地诽谤编译器。
FWIW,C++ 中的首选方法是使用匿名名称空间:
老实说,不,我不能指出这样做有很多客观优势......
A name that's static in each file should not cause name collisions. If you're seeing that, please post (short) demo code showing it, along with the exact compiler you're using so we can properly verify the code and assuming it's correct, proper vilify the compiler.
Just FWIW, the preferred method in C++ is to use an anonymous namespace instead:
In all honesty, no I can't point to a lot of objective advantage to that though...