c - extern int a; 之间的区别外部内部 a=42;

标签 c

当我阅读 Use of 'extern' keyword while defining the variable 的答案时

一位用户这样回答

 extern int a;       //  not a definition 
 extern int a = 42;  //  definition 

我原以为两者都不是定义而是声明。我在想这两个语句都说变量是在函数外部定义的,我们必须使用 extern 关键字才能使用它。这是他的错误还是真的是一个定义? 这个我知道

extern int a; // variable is already defined but its outside the function
extern int a=42 ; //I guess a variable is assigned a value but not a definition 

但是这些声明

extern int a = 42; // user said its a definition and now i got  confused

请用这些清除我。

最佳答案

无论何时尝试初始化,语句都会成为一个定义,无论是否使用externextern 关键字在这种情况下是多余的,因为默认情况下,未标记为 static 的符号已经具有外部链接。

声明一个外部变量并在当前编译单元中设置它的初始值是没有意义的,这是一个矛盾。

关于c - extern int a; 之间的区别外部内部 a=42;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7610321/

相关文章:

使用数据结构的 C 程序部分的复杂性和解释

c++ - 如何从pcap文件中获取域名地址和A记录?

c++ - pic vs vs pie之间的区别

c - MPI 矩阵矩阵乘法问题 : Cluster slower than single computer

c - 关闭与数据库的连接时不会释放内存(C,postgres - libpq)

python - ctypes python 中的浮点指针并传递结构指针

c - 在排序的字符串数组中找到一个字符串,其中也包含一些 NULL 字符串

c - 如何从正在执行可能抛出它的文件的 shell 脚本捕获信号?

c - doxygen 中是否可以提取函数注释并以 markdown 形式显示?

c - Windows COLOR_WINDOW 或 COLOR_BACKGROUND 的 RGB 颜色是什么?