hyuk myeong
hyuk myeong

Reputation: 325

Why same named extern local variables in different blocks get different linkages between compilers in c++?

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

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?

Upvotes: 11

Views: 248

Answers (1)

Davis Herring
Davis Herring

Reputation: 39963

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

Upvotes: 4

Related Questions