c - 将打印哪个值?

标签 c extern

void main()
{
    extern int i;
    printf("%d\n",i);
}
int i;//definetion
int i=35;//definition

上面代码中int i表示i=0;int i=35表示i=35.

那么,如果编译器没有给出 redefinition 错误,那么将打印哪个值?

最佳答案

在 ansi 标准中,他们称 int x; 为“暂定”定义。

这是 ansi 标准所说的:

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.

举例说明:

     int i1 = 1;          /*  definition, external linkage */
     static int i2 = 2;   /*  definition, internal linkage */
     extern int i3 = 3;   /*  definition, external linkage */
     int i4;              /*  tentative definition, external linkage */
     static int i5;       /*  tentative definition, internal linkage */
     int i1;   /*  valid tentative definition, refers to previous */
     int i2;   /*  $3.1.2.2 renders undefined, linkage disagreement */
     int i3;   /*  valid tentative definition, refers to previous */
     int i4;   /*  valid tentative definition, refers to previous */
     int i5;   /*  $3.1.2.2 renders undefined, linkage disagreement */



     extern int i1; /* refers to previous, whose linkage is external */
     extern int i2; /* refers to previous, whose linkage is internal */
     extern int i3; /* refers to previous, whose linkage is external */
     extern int i4; /* refers to previous, whose linkage is external */
     extern int i5; /* refers to previous, whose linkage is internal */

根据我的理解,您可以根据需要对同一对象拥有任意多个暂定定义,但最多只有一个定义(带有初始值设定项)。如果没有定义,则将暂定定义转换为文件末尾带有 initializer == 0 的定义。

换句话说,打印的值是35,因为有初始化器。

关于c - 将打印哪个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21184901/

相关文章:

python - 将函数从 Python 转换为 C

在与我的 C++ 类相同的 Visual Studio 解决方案中从 C 项目(共享库)调用 C 函数,出现链接器错误

c++ 全局变量未在此范围内声明

javascript - 我们可以在浏览器 session 中跨网页引用 JavaScript 变量吗?

c - 编写一个函数来计算 c 结构中的元素数量

使用宏的 C 枚举

python - 如何向 IGMP 设备发送 UDP 数据报?

c - Go中的地址对齐

c++ - extern的使用和防止重复定义

c++ - 如何在 C++ 中声明外部类指针?