Reputation: 6831
I recently ran into the problem described in Weird undefined symbols of static constants inside a struct/class and I am trying to bring my code into compliance by adding definitions to the corresponding .cpp files for all of my static const class members, not just the ones that were causing linker errors.
In the cases where the constant is used in multiple compilation units, I am getting multiple definition errors, even though the definition is only in one of the compliation units.
Moving the initializers to the definitions prevent the errors, but I would rather not do that.
For what it's worth, while I am currently working in Visual Studio, this code needs to build on several platforms.
Upvotes: 0
Views: 4609
Reputation: 96241
According to one of the posts on http://bytes.com/topic/c/answers/710704-const-static-initialization-visual-studio this may actually be a visual studio bug, preventing you from using that form of initialization.
Unfortunately I think you may be stuck doing the initialization in the source file to maintain portability.
I created a simple example that compiled and linked fine in g++ 4.2.
Upvotes: 1
Reputation: 206536
Static member variables are declared in the class body and defined once outside the class body. The general way of doing this is:
class MyClass
{
static int i;
};
int MyClass::i = 0;
The definition is done in the C++ source files and not in header(.h). If it is done so, the variable will defined everywhere the header file being included. It seems you are facing this very same problem.
Upvotes: 3
Reputation: 26104
If you have language extensions enabled, Visual Studio will allow you to use static const objects without defining the in an implementation file. Unfortunately, it will issue an error (if I remember correctly) for correct C++ programs, when there is an explicit definition.
Try to disable language extensions.
Upvotes: 1
Reputation: 14159
I think if you want your code to work on multiple platforms, you should move the initialisation to the definition (in the .cpp file). While it might work otherwise on one or more compilers, don't rely on it to be portable.
Upvotes: 0