Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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?

like image 557
hyuk myeong Avatar asked Apr 17 '20 16:04

hyuk myeong


People also ask

What are the types of linkages a internal and external b external internal and none C external and none D internal?

Explanation: External Linkage-> means global, non-static variables and functions. Internal Linkage-> means static variables and functions with file scope. None Linkage-> means Local variables.

What is a linkage variable in C?

In programming languages, particularly the compiled ones like C, C++, and D, linkage describes how names can or can not refer to the same entity throughout the whole program or one single translation unit. The static keyword is used in C to restrict the visibility of a function or variable to its translation unit.

What do you mean by internal linking and external linking in C++?

Internal linkage refers to everything only in scope of a translation unit. External linkage refers to things that exist beyond a particular translation unit. In other words, accessible through the whole program, which is the combination of all translation units (or object files).


1 Answers

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

like image 117
Davis Herring Avatar answered Oct 15 '22 23:10

Davis Herring