4

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.

scdmb
  • 15,091
  • 21
  • 85
  • 128

2 Answers2

8

Function declarations do have external linkage by default, so adding the extern keyword to a function declaration makes no difference, it is redundant.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

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( ); 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.

There's no harm in declaring the function extern: the linker does the right thing.

Pete Wilson
  • 8,610
  • 6
  • 39
  • 51
  • `tells the compiler and linker to look in another file when the code in this file refers to fun( )` I do not think this is correct. The compiler will produce a placeholder value for the function call _irrespectively_ of the `extern` type specifier. As stated in the correct answer, the `extern` specifier is redundant. If the compiler would do so by himself it would incoporate linker logic. The linker jobs is to go through the symbol tables and resolve the placeholder value with the final address of the function. – clickMe Jan 16 '18 at 15:13