Why is “static” needed for a global const char but not for a bool?

前端 未结 2 1813
抹茶落季
抹茶落季 2021-01-01 19:45

Shared header.

I can do this:

const bool kActivatePlayground=false;

Works fine when included among multiple files.

I cannot do t

相关标签:
2条回答
  • 2021-01-01 20:08

    In C++, const variables by default have static linkage, while non-const variables have external linkage.

    The reason for the multiple definitions error is that

    const char * kActivePlayground = "kiddiePool";
    

    creates a variable with external linkage.

    Hey wait, didn't I just say that const variables default to static linkage? Yes I did. But kActivePlayground is not const. It is a non-const pointer to const char.

    This will work as you expect:

    const char * const kActivePlayground = "kiddiePool";
    
    0 讨论(0)
  • 2021-01-01 20:24

    You can use a constant char array

    const char kActivePlayground[] = "kiddiePool";
    

    and kActivePlayground can also be used for assignment because it is a reference

    const char* playground_text = kActivePlayground;
    
    0 讨论(0)
提交回复
热议问题