VS2013 - static constant already defined

I have the following code (simplified) that compiles in gcc but gives an error in VS:

// main.cpp #include "test.h" int main() { return 0; } // test.h #pragma once class Test { static const int TEST = 3; }; // test.cpp #include "test.h" const int Test::TEST; 

Mistake:

 main.obj : error LNK2005: "private: static int const Test::TEST" ( ?TEST@Test @@0HB) already defined in test.obj 

Is this a VS error or is gcc incorrectly allowing me to explicitly define a static const member?

Update: found this in C ++ Standard (9.4.2.3):

If a constant statistic element with a constant stabilizer is integral or enumerable, its declaration in the definition class may indicate a bit-or-equal-initializer, in which each initializer clause, which is an assignment expression, is a constant expression (5.20). A static literal data member can be declared in a class definition using the constexpr specifier; if so, his declaration specifies a logical or equal-initializer in which each initializing clause, which is an assignment expression, is a constant expression. [Note: in both of these cases, a member may appear in constant expressions. - end note] A member must be defined in the namespace area if used in odr (3.2) in the program, and the namespace area definition must not contain an initializer.

Update # 2: an error report was found stating that it was fixed in the next major version.

+7
c ++ visual-studio visual-studio-2013
source share
2 answers

Exactly as you said, this is an MSVC error . The code compiles and works fine in Visual Studio 2015 RC with the default project settings.

enter image description here

The compiler considers "static const int TEST = 3;" and "const int Test :: TEST"; are two different definitions of the same variable. To fix this in your version, you can try setting the static value of the variable in the .cpp file:

 // test.h #pragma once class Test { static const int TEST; }; // test.cpp #include "test.h" const int Test::TEST = 3; 
+2
source share

With Microsoft Extensions for C and C ++ , the compiler automatically generates a definition outside the class. Some versions of compilers are probably wrong and make this automatic determination, even if you determined it manually (for example, when writing portable code).

You can disable extensions or check out the _MSC_EXTENSIONS macro. It is detected when the / Ze option is set. For example:

 #ifndef _MSC_EXTENSIONS const int MyClass::MyStaticMember; #endif 
+1
source share

All Articles