看了楼上john_lee的帖子,我意识到我前面说错了。
按作用域分,有 全局变量、文件变量、函数内变量,c++的大括号里面也可以定义变量。
a.c b.c c.c 三个文件,前两个里面都有个 int a; 都是全局变量。 第三个里面有个extern int a; 那么是用的哪个文件里面的呢? 所以前面我的回复是错误的。
static int a; 才是这个文件之内的,非全局的变量。参考c99的6.2.2的第三段。
无论哪个文件里面的全局变量,都是整个项目的全局变量。
6.9.2 的第二段 一个声明,如果是文件作用域,而且没有初始值,没有(typedef、extern、static、auto、register)前缀,则是个尝试性声明。如果最终没有找到声明,则给尝试声明加个声明,并赋值为0;
原文如下:
A declaration of an identifier for an object that has file scope without an initializer, and
without a storage-class specifier or with the storage-class specifier static, constitutes a
tentative definition. If a translation unit contains one or more tentative definitions for an
identifier, and the translation unit contains no external definition for that identifier, then
the behavior is exactly as if the translation unit contains a file scope declaration of that
identifier, with the composite type as of the end of the translation unit, with an initializer
equal to 0.
|