Best code to compile static const int = X in VS2008 and GCC

I had a problem writing C ++ code that needs to be compiled in Visual Studio 2008 and in GCC 4.6 (and also need to be compiled back in GCC 3.4): static const int members of the class.

Other questions have covered the rules needed for static members of the const int class. In particular, the standard and GCC require that a variable has a definition in one and only one object file.

However, Visual Studio generates an LNK2005 error when compiling code (in debug mode) that includes a definition in a .cpp file.

Some of the methods I'm trying to solve are as follows:

  • Initialize it with the value in the .cpp file, not the header.
  • Use the preprocessor to remove the definition for MSVC.
  • Replace it with a listing.
  • Replace it with a macro.

The last two options are not attractive, and I probably will not use them. The first option is simple - but I like to make a difference in the title.

What I'm looking for in the answers is a good, effective code structuring method that makes GCC and MSVC both happy. I hope for something wonderfully beautiful that I have not thought of yet.

+6
source share
4 answers

I usually prefer enum because it ensures that it will always be used as an instant value and that it will not receive any storage. It is recognized by the compiler as a constant expression.

 class Whatever { enum { // ANONYMOUS!!! value = 42; }; ... } 

If you cannot go this way, #ifdef open the definition in .cpp for MSVC, because if you refuse the value in the declaration, it will always receive memory; the compiler does not know the value, therefore, it cannot embed it (well, "generating the link time code" should be able to fix this if it is enabled) and cannot use it where a constant is needed, for example, value template arguments or array sizes.

+3
source

If you do not like the idea of ​​using non-standard hacks, for VC ++ always __declspec(selectany) . I understand that it ensures that during a connection any conflicts will be resolved by eliminating just one definition. You can put this in the #ifdef _MSC_VER block.

+2
source

Visual C ++ 2010 accepts this:

 // test.hpp: struct test { static const int value; }; // test.cpp: #include "test.hpp" const int test::value = 10; 
+1
source

This is still a problem with VS2013. I worked on this by putting my standard definition in the cpp file inside #if preventing VS.

hijras:

 class A { public: static unsigned const a = 10; }; 

a.cpp:

 #ifndef _MSC_VER unsigned const A::a; #endif 

I also commented on this well, so the next guy in the file knows which compiler is to blame.

0
source

Source: https://habr.com/ru/post/896351/


All Articles