C / C ++全球VS静态全局 [英] C/C++ global vs static global

查看:162
本文介绍了C / C ++全球VS静态全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  静态VS全球

我感到困惑全局和静态全局变量之间的差异。如果静态意味着这个变量只对同一文件是全球性的,那么为什么在两个不同的文件名称相同的原因名称冲突?

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 name collisions??

有人能解释一下吗?

推荐答案

全局变量(不是静态),在那里,当你创建的.o可供链接器使用的其他文件中使用文件。因此,如果有两个文件这样,你得到名称冲突 A

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 on a:

交流转换器:

#include <stdio.h>

int a;

int compute(void);

int main()
{
    a = 1;
    printf("%d %d\n", a, compute());
    return 0;
}

b.c:

int a;

int compute(void)
{
    a = 0;
    return a;
}

因为链接器不知道哪个全局 A s到使用。

然而,当你定义静态全局变量,你告诉编译器,以保持变量仅适用于文件,不要让连接器知道这件事。所以,如果你添加静态(在定义 A )的两个样本codeS我写的,你不会得到名称冲突仅仅是因为链接器甚至不知道有一个 A 无论是在文件:

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 of a) to the two sample codes I wrote, you won't get name collisions simply because the linker doesn't even know there is an a in either of the files:

交流转换器:

#include <stdio.h>

static int a;

int compute(void);

int main()
{
    a = 1;
    printf("%d %d\n", a, compute());
    return 0;
}

b.c:

static int a;

int compute(void)
{
    a = 0;
    return a;
}

这意味着,每个文件可以与自己的 A 在不知道其他的。

This means that each file works with its own a without knowing about the other ones.

作为一个侧面说明,它的确定将它们静态,其他没有限制,只要它们是在不同的文件之一。如果两个声明都是在同一个文件(阅读的翻译单元的),一个静态和一个的extern ,见这个答案

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), one static and one extern, see this answer.

这篇关于C / C ++全球VS静态全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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