我正在尝试基于 extern 的程序,据我所知,这在跨多个只有一个定义的文件访问变量时很有帮助。
但是我尝试了一个简单的程序,如下所示,没有 extern
当我预计它会在链接过程中失败时,事情似乎有效
文件5.c:
#include <stdio.h>
#include "var.h"
int a = 20;
int main() {
printf("\n File5.c a = %d", a);
test();
return 0;
}
文件6.c:
#include <stdio.h>
#include "var.h"
int test() {
printf("\n File6.c a = %d",a);
}
var.h
int a;
正如我已包含的那样var.h
在所有不带 extern 的头文件中,int a
将包含在 .c
中文件并且在链接期间,编译器应该抛出警告或错误消息,但它编译文件没有任何问题。
不应该var.h
有以下extern int a
?
最佳答案
header 通常最好使用 extern int a;
。另请参阅How do I share a variable between source files in C?
标准规定:
ISO/IEC 9899:2011 §6.9.2 External object definitions
Semantics
¶1 If the declaration of an identifier for an object has file scope and an initializer, the declaration is an external definition for the identifier.¶2 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.
因此, header 中的内容是变量的暂定定义。在 file5.c
的翻译单元 (TU) 末尾,您不再获得暂定定义; int a = 20;
指定的“外部定义”已经指定了这一点。在 file6.c
的 TU 末尾,您有一个相当于 int a = 0;
的定义。
当您尝试链接 file5.c
和 file6.c
时,您应该会遇到 a
的多个定义。然而,有一个共同的扩展,记录在附件 J 的标准中:
J.5.11 Multiple external definitions
¶1 There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword
extern
; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).
您的编译器正在提供 §J.5.11 标识的扩展,因此(合法地)不会提示。
580
关于c - 跨多个文件的变量访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18676376/