The fundamental problem (assuming that this really is what is
slowing you down, which would rather surprise me) is that you
have an instance of the variable in each translation unit that
includes the header. For int
, this probably isn't an issue,
but if any of the types have constructors, it definitely could
be. In general, except for integral constants, you probably
should not have static
in a header. (And be aware that if the
object itself is const, it is static by default.) Thus, for
a string, it should be:
namespace Msg
{
extern std::string const someMessage;
};
and then in a source file:
std::string const Msg::someMessage( "whatever" );
(The source file should, of course, include the header.)
Note that even with integral constants, you have to be careful;
if the use doesn't result in an immediate lvalue to rvalue
conversion, you will need an actual data declaration. In every
file that uses it in this way, since there is one instance per
file.
A perhaps better solution here would be to use a class, rather
than a namespace:
class Msg
{
public:
static int const msgType = 1;
static std::string const someMessage;
// ...
};
This ensures that there is only one actual instance, but still
allows integral constants to work as integral constant
expressions. (Here too, you need a single definition in
a source file somewhere.)