I have run into a problem while writing C++ code that needs to compile in Visual Studio 2008 and in GCC 4.6 (and needs to also compile back to GCC 3.4): static const int
class members.
Other questions have covered the rules required of static const int class members. In particular, the standard and GCC require that the variable have a definition in one and only one object file.
However, Visual Studio creates a LNK2005 error when compiling code (in Debug mode) that does include a definition in a .cpp file.
Some methods I am trying to decide between are:
- Initialize it with a value in the .cpp file, not the header.
- Use the preprocessor to remove the definition for MSVC.
- Replace it with an enum.
- Replace it with a macro.
The last two options are not appealing and I probably won't use either one. The first option is easy -- but I like having the value in the header.
What I am looking for in the answers is a good looking, best practice method to structure the code to make both GCC and MSVC happy at the same time. I am hoping for something wonderfully beautiful that I haven't thought of yet.