EXTERN与C变量的全局定义 [英] extern with global definition of variable in c

查看:133
本文介绍了EXTERN与C变量的全局定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下来源$ C ​​$ C这吸引我。

I have the following source code which interests me.

#include <stdio.h>
extern int foo;
int foo = 32;

int main()
{
printf("%d", foo);
}

这一个完全正常的一块code,而当我编译

This a perfectly normal piece of code, and when I compile it with

gcc -Wall -Wextra -pedantic foo.c

我没有得到任何警告。

I get no warnings.

和它似乎奇怪,因为一个变量被定义既作为外部,并且还全球在同一文件中。
我敢肯定,这很容易给链接器找到在同一文件中的外部变量的引用,但不会看起来像一个编码错误?如果是这样,为什么不编译器警告呢?

And it seems weird, because a variable is defined both as external, and also global in the same file. I'm quite sure that it's easy to the linker to find the reference for the external variable in the same file, but doesn't it look like a coding error? And if so, why doesn't the compiler warn about this?

推荐答案

有什么奇怪的。你首先做了一个变量声明(你答应它存在的编译器),然后你真正定义它。有没有问题,即

There's nothing weird. You first made a declaration of a variable (you promised the compiler that it exist) and then you actually defined it. There's no problem in that.

此外,在默认情况下,是不是本地的功能,并没有定义为静态所有变量都的extern

Also, by default, all variables that aren't local to functions and aren't defined as static are extern.

这篇关于EXTERN与C变量的全局定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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