isocpp / CppCoreGuidelines

The C++ Core Guidelines are a set of tried-and-true guidelines, rules, and best practices about coding in C++
http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
Other
42.69k stars 5.44k forks source link

Are extern local variables safe to use? #1604

Closed ghost closed 4 years ago

ghost commented 4 years ago

Hello,

Why don't we add some guideline for not using extern local variables?

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

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 a related phrase in the standard
but it is still unclear to me because its behavior is different by compilers
(https://eel.is/c++draft/basic.link#6)

I don't know that which compilers are conforming the standard well
and do you think that it is helpful to add some guide about it?

shaneasd commented 4 years ago

It seems like this example violates http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es12-do-not-reuse-names-in-nested-scopes . Is there an example that doesn't?

ghost commented 4 years ago

Aha, there it is It looks es12 covers this problem Thank you! I will check a bit more and close this issue