简体   繁体   English

功能声明与extern和没有它的区别

[英]Difference between declaration of function with extern and without it

There is such code: 有这样的代码:

#include <iostream>

extern void fun();

int main(){
    fun();
    return 0;
}

void fun(){ std::cout << "Hello" << std::endl; }

Is there some difference between declarations: 声明之间是否存在一些差异:

extern void fun();
void fun();

? Code above behaves the same with extern and without extern keyword. 上面的代码与extern和没有extern关键字的行为相同。

默认情况下,函数声明确实有外部链接 ,因此将extern关键字添加到函数声明没有任何区别,这是多余的。

The difference between the two statements is this: 这两个陈述之间的区别是:

extern void fun();

tells the compiler and linker to look in another file when the code in this file refers to fun( ), perhaps by calling fun( ); 当这个文件中的代码引用fun()时,告诉编译器和链接器查看另一个文件,可能是通过调用fun(); This production is called a "declaration." 这种生产被称为“宣言”。

void fun ( ) {
  ...
}

Defines the function fun ( ) and, because it's defined in this file, obviates the need for the linker to look for the function elsewhere. 定义函数fun(),因为它在此文件中定义,所以不需要链接器在其他地方查找函数。

There's no harm in declaring the function extern: the linker does the right thing. 声明函数extern没有坏处:链接器做正确的事情。

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

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