tags:

views:

138

answers:

1

I know that static const int x = 42; at namespace scope is equivalent to const int x = 42; because const variables are implicitly static (they must be declared extern to be given external linkage). Every translation unit that includes this declaration gets a local copy of x.

Does this only apply to certain (perhaps integer?) types? I have the following code in a header file:

namespace XXX {
    static const char* A = "A";
    static const char* B = "B";
    static const char* C = "C"; // and so on
}

(PLEASE spare me the comments on why I should not be using C-style strings -- this is legacy code)

This header is included from several source files, and all is fine (each compilation unit gets its own copy of these char*'s). I would have thought that I could remove the static from these, as it is redundant, but when I do, I get link errors about the symbols being already defined in another object. What am I missing here? Are these const char*'s not implicitly static?

+15  A: 

In your example, you are creating a pointer to a constant (block of) char rather than creating a constant pointer to a char. Thus, your pointer isn't constant and so isn't implicitly static.

You need to declare x as const char *const A, which creates a constant pointer to a constant (block of) char.

David Pfeffer
Yes. That'll create a constant pointer to a block of constant chars, which is what you'd want for a string literal.
David Pfeffer