我知道这是一个基本问题,不确定 c 标准是否允许这样做。我在面试中得到了一个代码片段,并被要求提供输出。
我在一个函数中声明了一个同名的外部变量和一个局部变量,它抛出一个重新声明错误(就像全局变量一样)可能是什么原因?因为 i 是在同一个 block 中声明的,extern 应该能够找到它吗?
#include <stdio.h>
int main(void){
int i = 10;
extern int i ;
printf("%d \n",i);
}
Error : 1.c: In function ‘main’:
1.c:13: error: extern declaration of ‘i’ follows declaration with no linkage
1.c:12: note: previous definition of ‘i’ was here
最佳答案
int i = 10;
extern int i ;
第一个,因为它是函数作用域,意思是“声明并定义一个函数局部变量i
”。变量应该没有链接,因为它是函数局部的;具体来说(C11 6.2.2 第 6 段):
The following identifiers have no linkage: [ ... ]; a block scope identifier for an object declared without the storage-class specifier extern.
另一方面,第二条语句是“声明一个具有外部链接的变量 i
”。
在一定的限制范围内,允许重新声明一个变量,但一般来说声明必须保持一致;以上两种说法自相矛盾。此外,不能重新声明没有链接的标识符 - 来自 C11 6.7 第 3 段:
If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space
(之后列出了一些异常(exception)情况,但它们与此处无关)。
如果语句在函数外部(在文件范围级别),则 int i = 10;
声明将指示外部链接,因此以下声明是一致的 -事实上,它甚至不需要保持一致,因为 6.2.2 第 4 段适用:
For an identifier declared with the storage-class specifier
extern
in a scope in which a prior declaration of that identifier is visible, 31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.
(因此,在文件范围内声明 static int i = 0; extern int i;
是完全合法的 - 尽管声明不一致,但上述规则允许第二种声明,尽管我不知道这样做的理由。但是,您不能以相反的顺序进行这些陈述)。
关于c - 外部内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378826/