I have a class in MyClass.h file:
// MyClass.h
#ifndef __MY_CLASS_H__
#define __MY_CLASS_H__
#include <string>
class MyClass
{
static const std::string MyStaticConstString; // I cannot initialize it here, because it's not an integral type.
};
// OK, let's define/initialize it out side of the class declaration
// static
const std::string MyClass::MyStaticConstString = "Value of MyStaticConstString";
#endif
The problem is, the compiler will complain “Multiple definition” if this file is included for more than one times.
So I have to move the definition of MyStaticConstString to MyClass.cpp file. But what if MyClass is part of a library, and I want my users to see the const static value in the MyClass.h file, which makes sense, because it’s a static const value.
How should I do? I hope I made myself clear.
Thanks.
Peter
No, for the same reason you can’t put global variables in headers, const-qualified or not. Document your constant instead (if it’s a constant, then why should users care about its value anyway?).
Also, don’t prepend your identifiers with underscores (
__MY_CLASS_H__), they’re reserved for implementation stuff.