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

前端 未结 3 1940
遇见更好的自我
遇见更好的自我 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条回答
  •  萌比男神i
    2021-02-05 12:21

    The first method is indeed wrong, since it makes a definition of an object COUNTRY_NAME_USA with external linkage in the header file. Once that header file gets included into more than one translation unit, the One Definition Rule (ODR) gets violated. The code will fail to compile (more precisely, it will fail to link).

    The second method is the correct one. The keyword extern is optional in the definition though, i.e. in the cpp file you can just do

    const char* COUNTRY_NAME_USA = "USA"
    

    assuming the declaration from the header file precedes this definition in this translation unit.

    Also, I'd guess that since the object name is capitalized, it is probably intended to be a constant. If so, then it should be declared/defined as const char* const COUNTRY_NAME_USA (note the extra const).

    Finally, taking that last detail into account, you can just define your constant as

    const char* const COUNTRY_NAME_USA = "USA"; // no `extern`!
    

    in the header file. Since it is a constant now, it has internal linkage by default, meaning that there is no ODR violation even if the header file is included into several translation units. In this case you get a separate COUNTRY_NAME_USA lvalue in each translation unit (while in extern method you get one for the entire program). Only you know what you need in your case .

提交回复
热议问题