gpt4 book ai didi

c - 即使没有声明也使用全局定义

转载 作者:行者123 更新时间:2023-12-02 06:28:09 25 4
gpt4 key购买 nike

在这段代码中:

#include<stdio.h>

int var=100;

int main()
{
extern int var; //Declaration not Definition
printf("%d\n",var);
return 0;
}

100 被打印出来,这并没有什么不正常,但是当从 ma​​in() 中删除声明时,即使这样也会使用全局定义。这是怎么回事?这取自 K&R,它说:

The (global) variable must also be declared in each function that wants to access it.

最佳答案

对于在同一文件或模块中声明的变量,无需包含 extern 关键字。全局变量对 main 可见,因为它具有全局范围(即它对文件/模块中的所有函数可见)。

To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files.

Source

关于c - 即使没有声明也使用全局定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49477416/

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