Difference between function declaration with external and without it

There is a code like this:

#include <iostream> extern void fun(); int main(){ fun(); return 0; } void fun(){ std::cout << "Hello" << std::endl; } 

Is there a difference between the ads:

 extern void fun(); void fun(); 

? The code above behaves the same as extern and without the extern keyword.

+4
source share
2 answers

A function declaration has an external default binding , so adding the extern keyword to a function declaration does not matter, it is superfluous.

+7
source

The difference between the two statements is as follows:

 extern void fun(); 

tells the compiler and linker to look in another file when the code in this file refers to fun (), possibly by calling fun (); This work is called a "declaration."

 void fun ( ) { ... } 

Defines the fun () function, and since it is defined in this file, eliminates the need for the linker to look for the function elsewhere.

There is no harm in declaring an extern function: the linker is doing the right thing.

+2
source

All Articles