重新初始化已经在其他源文件中定义的全局变量 [英] reinitialize a global variable that is already defined in other source file

查看:135
本文介绍了重新初始化已经在其他源文件中定义的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,只是一个关于全局变量的问题,下面是按建议使用头文件的代码:

I'm new to C, just a question on global variable, below is the code that uses the header file as recommended:

//test.h

extern int globalVariable;

//test.c

#include "test.h"

int globalVariable = 2020;

//main.c

#include <stdio.h>
#include "test.h" 

int main()
{
   printf("Value is %d", globalVariable);
}

因此运行良好,打印输出为2020.

so it works well and the print output is 2020.

但是如果我将main.c更改为:

#include <stdio.h>
#include "test.h" 

int globalVariable;

int main()
{
   printf("Value is %d", globalVariable);
}

它仍然可以编译,并且输出仍然是2020.下面是我的问题:

it still compile and the output is still 2020. Below is my question:

Q1-当我在main.c中添加int globalVariable;时,并不是因为int globalVariable;int globalVariable = 0;相同,它会将globalVariable重新初始化为0.那么为什么输出仍然是2020年而不是0?

Q1-When I add int globalVariable; in main.c, isn't that it re-initialize the globalVariable to 0 becuase int globalVariable; is the same as int globalVariable = 0;. So why the output is still 2020 rather than 0?

Q2- globalVariable,我将其重新定义(重新初始化)为0,这是编译错误,因为C不允许多重定义,所以为什么程序仍然可以编译?

Q2-globalVariable is already defined in test.c, and I re-define(reinitialize) it to 0, should it be a compile error since C doesn't allow multiple definition, so why the program still compile?

推荐答案

此声明在文件范围内:

int globalVariable;

临时定义.它没有初始化程序,也不是static. GCC可以折叠"从多个翻译单元到单个标识符的初步定义.这不是标准规定的,而是GCC支持的扩展.

Is a tentative definition. It has no initializer and is not static. GCC can "fold" tentative definitions together from multiple translation units into a single identifier. This is not specified by the standard but is an extension supported by GCC.

在这种情况下,main.c中的暂定定义将汇总到test.c中的完整定义,并使用给定值进行初始化.如果还要在main.c中使用初始化程序,则会收到多定义错误.

In this case the tentative definition in main.c gets rolled into the the complete definition in test.c and initialized with the given value. If you were to use an initializer in main.c as well, then you would get a multiple definition error.

这篇关于重新初始化已经在其他源文件中定义的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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