Should a const static variable be initialized in a c++ header file?
c++, declaration, initialization, static
Solution
why is this when I have been using guard macro already?
Header guards only prevent the inclusion of the header file contents more than once in the same translation unit not across multiple translation units.
why is `A::a` does not have the error message (I can't write code `const static obj b={1,2}` in `class A`)
In-class initialization is allowed by the compiler as a special case for static data members of const literal type. Your example one is In-class initialization.
`const A::b` defines the same symbol name in each translation unit where the header gets included and hence breaks the one definition rule.
You need to move the definition to one and only one source cpp file so that it gets defined only once.
Problem
my_test.h ``` #ifndef MY_TEST #define MY_TEST struct obj { int x; int y; }; class A { private: const static int a=100; const static obj b; }; const obj A::b={1,2}; #endif ``` When compiling cpp using this header file, an error `'multiple definition of 'A::b'` occurs. - why is this when I have been using guard macro already? - why does `A::a` not produce the erro? (I can't write code `const static obj b={1,2}` in `class A`)