据我所知,C 中的对象有 3 种类型的链接:1) 外部 2) 内部和 3) 无,并且在 block 范围内声明的对象,如在函数体内,没有链接,除非前面有关键字“外部”或“静态”。
但为什么下面的函数声明能够链接到 main() 函数下面的定义,即使我在声明期间没有使用“extern”?请对此进行解释,因为它颠覆了我对该主题的全部理解。谢谢。
#include<stdio.h>
int main()
{
int foo(); //working even though I've not used "extern"
printf("%d",foo());
}
int foo()
{
return 8;
}
上述程序的结果:8
最佳答案
and that objects declared at block scope, as within a function body, have no linkage unless preceded with the keyword "extern" or "static".
函数不是对象。
C11 中的 6.2.2 说
-5- If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier
extern
. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
第一句话说在文件范围内声明的函数就好像用extern
声明的一样。即使在 block 范围内声明,这也适用。下一段是:
-6- The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier
extern
.
也就是说, block 作用域对象没有链接,但没有函数。
在 ISO C 中不能有嵌套函数,所以如果它不引用 block 外的东西,那么声明 block 作用域函数是没有意义的。
关于c - 在 C 中,如果在 block 范围内声明的对象没有链接,为什么没有 "extern"的 main() 中的函数声明有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25608399/