11

While I was just checking which linkages are granted to extern local variables
I found that some different behavior between compilers

for instance if I tested below code
as you see in the comments variable vars have different linkages

// foo.cpp
int var = 10;                // external linkage

// main.cpp
#include <iostream>

static int var = 100;        // internal linkage

int main() {
    extern int var;          // internal linkage
    std::cout << var << std::endl;
    {
        extern int var;      // g++: external linkage , clang++: internal linkage
        std::cout << var << std::endl;
        {
            extern int var;  // g++: external linkage , clang++: internal linkage
            std::cout << var << std::endl;
        }
    }
}       

the result is

  • g++ : "100 10 10"
  • clang++, msvc++ : "100 100 100"

I can see from the result that if there are more than two nested blocks
g++ just grants external linkages to variables

I could find related phrase in the standard
but it is still unclear because its behavior is different by compilers
(https://eel.is/c++draft/basic.link#6)

I'm afraid that my English is bad so I can't get it correctly
If someone have an idea that which compilers are conforming the standard well
and if possible could someone elaborate what the standard says exactly for me?

hyuk myeong
  • 197
  • 1
  • 13
  • 1
    Related https://stackoverflow.com/questions/41978949/linkage-of-function-declared-as-extern-in-block-scope-according-to-the-c17-s I believe it's a gcc bug, standard gives the example with `f()` function and the innermost `extern void f()` has internal linkage - `var` should have internal linkage here too, because it refers to the same "entity". – KamilCuk Apr 20 '20 at 17:41
  • IMO block scope declarations of entities with external linkage are Evil and the language would be better off with banning them – M.M Apr 25 '20 at 01:49
  • @M.M: Module units do so! – Davis Herring Apr 27 '20 at 21:42

1 Answers1

4

This is the subject of the open issue CWG1839. The current intent is that the behavior of Clang and MSVC is correct.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76