问题描述
我已经看到人们使用两种方法来声明和定义char *
.
I have seen people using 2 methods to declare and define char *
.
方法1:头文件具有以下内容
Medhod 1: The header file has the below
extern const char* COUNTRY_NAME_USA = "USA";
第2种方法:
头文件具有以下声明:
Medhod 2:
The header file has the below declaration:
extern const char* COUNTRY_NAME_USA;
cpp文件具有以下定义:
The cpp file has the below definition:
extern const char* COUNTRY_NAME_USA = "USA";
- 方法1是否在某种程度上错误?
- 两者之间有什么区别?
- 我了解"
const char * const var
"和"const char * var
"之间的区别.如果在上述方法中,如果像方法1那样在标头中声明并定义了"const char * const var
",那会有意义吗?
- Is method 1 wrong in some way ?
- What is the difference between the two ?
- I understand the difference between "
const char * const var
" , and "const char * var
". If in the above methods if a "const char * const var
" is declared and defined in the header as in method 1 will it make sense ?
推荐答案
第一种方法确实是错误的,因为它对具有外部的对象COUNTRY_NAME_USA
进行了定义. >头文件中的链接.一旦该头文件包含在多个翻译单元中,就会违反一个定义规则"(ODR).该代码将无法编译(更确切地说,将无法链接).
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).
第二种方法是正确的.关键字extern
在定义中是可选的,即在cpp文件中您可以执行
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.
此外,我猜想由于对象名称是大写的,因此可能打算将其作为常量.如果是这样,则应将其声明/定义为const char* const COUNTRY_NAME_USA
(请注意额外的const
).
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`!
头文件中的
.由于现在是常量,因此默认情况下具有内部链接,这意味着即使头文件包含在多个转换单元中也不会违反ODR.在这种情况下,每个翻译单元中都有一个单独的COUNTRY_NAME_USA
左值(而在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 .
这篇关于将值设置为"const char *"是否合适?在头文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!