gpt4 book ai didi

c - C 编程中使用 extern 进行声明和定义

转载 作者:行者123 更新时间:2023-12-04 09:30:20 25 4
gpt4 key购买 nike

这可能看起来很简单,但这个问题在很多方面都让我感到烦恼。

  1. 我的问题是关于 c 中变量的声明和定义。

关于这个问题,网上其实有很多解释,而且这个问题的解决方案并不只有一种,因为这个问题有很多观点。我想知道这个问题的明确存在。

int a;

就看这是一个声明还是定义?,当我使用printf时,它的值是0,地址是2335860 >。但如果这个声明那么为什么要为此分配内存。

int a;
int a;

当我这样做时,它说之前的“a”声明在这里,并且重新声明了“a”,没有链接。

  • 一些消息来源说 c 中允许重新声明,而另一些消息来源则说事实并非如此?

  • 最佳答案

    int a; just take this is this a declaration or definition?

    int a; 如果写在全局范围内是一个暂定定义。这意味着如果当前编译单元中没有其他可用的定义,则将其视为定义,否则这是一个声明。

    来自 C11 规范中的 6.9.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.

    int i4; // tentative definition, external linkage
    static int i5; // tentative definition, internal linkage

    因此,您实际上进行了多个声明,但由于暂定定义规则而获取了地址和值。

    some sources say redeclaration is permitted in c and some say dont what is the truth?

    C 中允许重新声明。但重新定义则不然。

    相关问题:What is the difference between a definition and a declaration?

    there are actually many explanation in internet

    更喜欢一本好书而不是互联网来掌握语言。您可以从以下内容中选择一本好书: The Definitive C Book Guide and List

    关于c - C 编程中使用 extern 进行声明和定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30978021/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com