本文介绍了为什么使用“ extern”创建变量是声明而不是定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读时遇到了以下问题...只是无法理解其背后的逻辑。

  auto int c; 
static int c;
register int c;
extern int c;

假设前三个是定义,最后一个是声明..为什么? p>

解决方案

最后一个带有 extern 的存储库未定义<$ c $的存储c> c 。它仅表示 c 在某处存在,并且链接程序应该能够将其解析为在其他位置定义的某些全局 c 。 / p>

如果编译并链接了一个.c文件,并尝试使用最后一个 c ,则将具有链接器错误。对于前3个 c ,您将不会因为它们在当前编译单元中具有实质内容(已被定义)。



如果您想了解有关 extern 和声明与定义的更多信息,请使用。引用该文章:


I came across the following problem while reading ...just cant get the logic behind this.

auto int c;
static int c;
register int c;
extern int c;

It is given that the first three are definition and last one is declaration ..how come ?

解决方案

The last one with extern does not define storage for c. It merely indicates that c exists somewhere and the linker should be able to resolve it to some global c defined elsewhere.

If you compiled and linked a single .c file and tried to use the last c you'd have a linker error. With the the first 3 cs you would not as they have substance (they've been defined) in the current compilation unit.

If you'd like to learn more about extern and declaration vs definition here's a good article on the topic. To quote from that article:

这篇关于为什么使用“ extern”创建变量是声明而不是定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:38