在 c 语言中, int a;是 declaration 还是 definition

49 天前
 rookiemaster

已知 extern int a;是 declaration

1854 次点击
所在节点    C
13 条回复
febhfrswsz
49 天前
然后呢
kk7896
49 天前
definition
rookiemaster
49 天前
又看到了一个东西叫 Storage-class specifiers ,好复杂
nyxsonsleep
49 天前
以下示例演示的声明也是定义:

C++

// Declare and define int variables i and j.
int i;
int j = 10;

下面这些声明不是定义:

C++

extern int i;
char *strchr( const char *Str, const char Target );

https://learn.microsoft.com/zh-cn/cpp/cpp/declarations-and-definitions-cpp?view=msvc-170
vituralfuture
49 天前
定义,因为分配了内存
realJamespond
49 天前
在头文件是声明,在源文件是定义
FranzKafka95
48 天前
赞同楼上的
mintist
48 天前
有内存空间分配就是定义,声明对应汇编的符号,仅仅为了告诉你有这个东西在这里
PTLin
48 天前
koebehshian
48 天前
The C Programming Language 附录 A ,A.8 Declarations 中说:

```
Declarations specify the interpretation given to each identifier; they do not necessarily reserve storage associated with the identifier. Declarations that reserve storage are called definitions.
```

所以,首先要明白,definition 是 declaration 的一种,区别在于 definition 为变量预留了内存
所以,你的问题应该修改为:int a; 有没有预留内存。

答案是:大多数情况下预留了内存。只有一种情况,就是写在函数外面

A.10.2 External Declarations 中说:

```
An external object declaration that does not have an initializer, and does not contain the extern specifier, is a tentative definition. If a definition for an object appears in a translation unit, any tentative definitions are treated merely as redundant declarations.
```

意思是,int a; 写在函数外面,编译器先会将其待定;如果发现整个编译单元(一般是一个预处理过的源文件)中有多个这样的写法,则多余的就被当作没有预留内存的 declarations 了
LGA1150
46 天前
@realJamespond
没有 extern 的话,即使在头文件里也是定义
hkdcl
46 天前
定义。函数外面的全局变量会初始化为 0 ,里面的会是该内存原来的值
pagxir
42 天前
@realJamespond #6 事实上 c 语言编译器眼里并不存在头文件一说,你可以把.h 改名成.c , 并在另一个 c 文件里 include 它

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1026188

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX