Should the static variable const be initialized in the C ++ header file?

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, a 'multiple definition of 'A::b' error occurs.

  • Why is this when I already used a protective macro?
  • Why is A::a not creating erro? (I cannot write const static obj b={1,2} code in class A )
+7
source share
4 answers

why is it when i already used a protective macro?

Header protectors prevent the contents of the header file from being included more than once in the same block not through a few translation units.

why A::a does not have an error message (I cannot write the code const static obj b={1,2} in class A )

Initialization inside the class is allowed by the compiler as a special case for static data elements of type const literal. Your example is initialization inside a class.

const A::b defines the same symbol name in each translation unit, where the header is included and, therefore, breaks one definition rule .

You need to move the definition to one and only one source cpp file so that it is defined only once.

+4
source

Alok has already answered your question, but here are a few simple rules of thumb: in a convenient form to remember:

  • Ads in the .h file
  • Definitions are included in the .cpp file

Therefore, static members must be declared in the .h file and then defined in the .cpp file. In your case, correct the syntax of the declarations, and then move them to the file "my_test.cpp".

+1
source

The problem is that your definition of A::b does not contain a type. For a correct definition, this should be:

 const obj A::b = {1, 2}; 

This will save you a compilation error, but you will still get linker errors if you include this header in more than one source file, because A::b will then propagate. You must transfer the definition to a .cpp file.

0
source

Regardless of whether you have header protection or not, placing this initialization in the header file means that you will get an A::b instance in every source file that includes this header file. Hence the linker error.

So, generally speaking, this is possible, but not a good idea.

0
source

All Articles