简体   繁体   中英

Isn't a const variable at namespace scope implicitly static?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM