0

I observe different behaviour of GNU C++ (version 9.4.0) and MSVC (version 19.32.31332.0) when I declare an extern variable inside a member function of a class defined inside a namespace. If it is a regular function the behaviour is the same.

The GNU compiler requires the variable to be defined inside the same namespace, while MSVC requires it to be defined outside of it.

Here is the MWE:

main.cpp:

    #include "some_class.h"

    // int var = 123; // compiles with MSVC
    
    namespace some_namespace
    {
        int var = 123; // compiles with GCC
    }
    
    int main()
    {
        some_namespace::some_class a{};
    
        a.print();
    }

some_class.h:

    #ifndef some_class_h
    #define some_class_h
    
    #include <iostream>
    
    namespace some_namespace
    {
        class some_class
        {
        public:
            void print(void)
            {
                extern int var;
    
                std::cout << "var: " << var << '\n';
            }
        };
    }
    
    #endif

Why does MSVC consider the variable to be declared outside of the namespace?

honey_badger
  • 472
  • 3
  • 10

0 Answers0