2

When I compile the following sources on VC++ 10, The i with static linkage gets assigned to 42 But on G++ 4.5.1, The i with external linkage in source2.cpp gets assigned to 42.

Any ideas on what should be the standard confirming behavior according to the Standard or why?

// source1.cpp

#include <iostream>

static int i = 0;

int h();
void foo()
{
     int i;
     {
         extern int i;
         i = 42;
     }
}

int main()
{
    foo();

    std::cout << i << std::endl;
    std::cout << h() << std::endl;
}

// source2.cpp

int i;
int h() { return i; }
cpx
  • 17,009
  • 20
  • 87
  • 142

1 Answers1

2

ISO/IEC 14882:2011 3.5/6:

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.

Inside the inner block in foo(), The declaration int i; hides the declaration at global namespace scope: static int i; so there is no visible i with linkage inside the inner block. This means that extern int i; refers to an entity with external linkage in the namespace immediately enclosing foo().

The assignment should affect the i with external linkage (defined in source2.cpp), it should have no effect on the i with internal linkage defined in source1.cpp.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656