Is it appropriate to set a value to a “const char *” in the header file

前端 未结 3 1843
遇见更好的自我
遇见更好的自我 2021-02-05 11:40

I have seen people using 2 methods to declare and define char *.

Medhod 1: The header file has the below

extern const char* COUNTRY_NAME_US         


        
3条回答
  •  孤街浪徒
    2021-02-05 12:27

    What's the point?

    If you want to lookup strings (that could be localized), this would be best:

    namespace CountryNames {
        const char* const US = "USA";
    };
    

    Since the pointer is const, it now has internal linkage and won't cause multiple definitions. Most linkers will also combine redundant constants, so you won't waste space in the executable.

    If you want to compare strings by pointer equality though, the above isn't portable because the pointers will only be equal if the linker performs the constant-folding optimization. In that case declaring an extern pointer in the header file is the way to go (and it again should be const if you don't intend to retarget it).

提交回复
热议问题