简体   繁体   English

在C中,如果在块作用域中声明的对象没有链接,为什么main()中的函数声明没有“extern”工作?

[英]In C, if objects declared at block scope have no linkage, why does function declaration inside main() without “extern” work?

As I know it, objects in C have 3 types of linkages: 1)external 2)internal and 3)none, and that objects declared at block scope, as within a function body, have no linkage unless preceded with the keyword "extern" or "static". 据我所知,C中的对象有3种类型的链接:1)外部2)内部和3)无,并且在块范围内声明的对象,如在函数体内,没有链接,除非前面有关键字“extern”或“静态”。

But why then the function declaration below is able to link to the definition below the main() function even though I've not used "extern" during declaration? 但是为什么然后下面的函数声明能够链接到main()函数下面的定义,即使我在声明期间没有使用“extern”? Please explain this as it is throwing my whole understanding of the topic upside down. 请解释一下,因为它完全颠覆了我对这个主题的理解。 Thank you. 谢谢。

#include<stdio.h>

int main()
{
int foo();  //working even though I've not used "extern"
printf("%d",foo());
}

int foo()
{
return 8;
}

RESULT OF ABOVE PROGRAM: 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". 并且在块作用域中声明的对象(如在函数体内)没有链接,除非前面带有关键字“extern”或“static”。

Functions are not objects. 函数不是对象。

6.2.2 in C11 says 6.2.2在C11中说

-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 . -5-如果函数的标识符声明没有存储类说明符,则确定其链接与使用存储类说明符extern声明的完全相同。 If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external. 如果对象的标识符声明具有文件范围而没有存储类说明符,则其链接是外部的。

THe first sentence says a function declared at file scope is as if declared with extern . 第一句话说在文件范围声明的函数就好像用extern声明一样。 That applies even if declared at block scope. 即使在块范围内声明,这也适用。 The next paragraph is: 下一段是:

-6- The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; -6-以下标识符没有链接:声明为对象或函数以外的任何标识符; an identifier declared to be a function parameter; 声明为函数参数的标识符; a block scope identifier for an object declared without the storage-class specifier extern . 没有存储类说明符extern声明的对象的块作用域标识符。

That says block-scope objects have no linkage, but not functions. 这表示块范围对象没有链接,但没有函数。

You can't have nested functions in ISO C, so it would make no sense to be able to declare a block-scope function if it didn't refer to something outside the block. 你不能在ISO C中使用嵌套函数,因此如果它没有引用块外的东西就能声明一个块作用域函数是没有意义的。

Functions are not objects. 函数不是对象。 So what you say about objects doesn't apply to functions. 所以你对对象的看法并不适用于函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM