简体   繁体   中英

Difference between local/block-scope declaration of function with extern and without it

It appears that in C++ extern (NOT followed by a language-linkage string literal) makes no difference on function declarations at namespace scope ( Difference between declaration of function with extern and without it ). But does it have any effect whatsoever on block scope function declarations? Or is a local function declaration without extern always equivalent to one with extern ?

namespace {
  void f() {
     extern void g(); // has external linkage
     g();
  }
  void f2() {
     void g();        // always the same, as if, without extern
     g();
  }
}

Thanks!

The rules here come from [basic.link]:

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage.

So there is no difference between a block scope function declaration with and without external . But note the interesting example:

 static void f(); void g() { extern void f(); // internal linkage } 

Here, the block scope f redeclares ::f and receives its same linkage: internal. Even though it's marked extern . But the presence of absence of the extern keyword is immaterial

Whether a function has the extern specifier or not in any case it has external linkage (if it is not explicitly declared as having internal linkage).

However a local function declaration can hide other function declarations with the same name in the outer scope.

Consider the following demonstrative program

#include <iostream>

void f( int ) { std::cout << "F( int )" << std::endl; }
void f( short ) { std::cout << "f( short )" << std::endl; }

int main() 
{
    void f( short );

    f( 10 );

    return 0;
}

Its output is

f( short )

If to comment the local declaration then the output will be

F( int )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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