简体   繁体   English

在标头中定义const字符串数组

[英]Define const string array in header

I would like to define something like that in a global header: 我想在全局标头中定义类似的内容:

namespace FruitSaladApp
{
    enum Fruits { Banana, Apple, Orange, Kiwi };
    const char * fruitStrings[] { "Banana", "Apple", "Orange", "Kiwi" };
}

I use header guards so that it gets defined only once per compilation unit. 我使用标题保护,以便每个编译单元仅对其定义一次。

I would like to keep the definition beside the enum to avoid getting them "out of sync" upon adding/deleting/modifying items, so that doing fruitStrings[Banana] is coherent and safe. 我想将定义保留在枚举旁边,以避免在添加/删除/修改项目时使它们“不同步”,以便使fruitStrings[Banana]连贯且安全。

You did define this array inside a namespace, not in a global scope. 您确实在名称空间内而不是在全局范围内定义了此数组。 Add static keyword before array definition and it should work. 在数组定义之前添加static关键字,它应该可以工作。

Explanation: By definition const variables declared in global namespace are static , so that gives them internal linkage (they are not visible in other .cpp files/translation units). 说明:根据定义,在全局名称空间中声明的const变量是static ,因此使它们具有内部链接(在其他.cpp文件/翻译单元中不可见)。 But const variables defined inside namespace are not static - this is not necessary, since namespace itself limits their visibility. 但是在名称空间内定义的const变量不是static -这不是必需的,因为名称空间本身限制了它们的可见性。 But when such header file is included twice or more in project, then symbol inside namespace is being declared twice or more in that namespace, which gives error of multiple definition. 但是,当这样的头文件在项目中包含两次或两次以上时,则在该命名空间中声明名称空间内的符号两次或多次,这会产生多个定义错误。

I thought that multiple definitions of const variables in c++ was allowed from this question 我认为这个问题允许c ++中const变量的多个定义

That question, and internal linkage in general, implies that you may define them once in multiple translation units each. 该问题以及总体上的内部联系意味着您可以在多个翻译单元中分别定义一次

You will still get multiple definition error if you define it multiple times in a single translation unit. 如果在单个翻译单元中多次定义它,您仍然会遇到多个定义错误。 Solution: Use header guards... Since you claim to use header guards, then the problem is either: incomplete example, or mistake in the header guards, or bad compiler. 解决方案:使用标题保护措施...由于您声称要使用标题保护措施,因此问题可能是:示例不完整,标题保护措施错误或编译器错误。

Actually, it requires the pointer to be const, not the pointed-to chars 实际上,它要求指针是const,而不是指向字符

namespace FruitSaladApp
{
    enum Fruits { Banana, Apple, Orange, Kiwi };
    const char * const fruitStrings[] { "Banana", "Apple", "Orange", "Kiwi" };
}

The initial question contained already that const but due to qmake, which is sometimes awkward for handling incremental build, some cpp files which included that header indirectly were not recompiled. 最初的问题已经包含了该const但是由于qmake有时对于处理增量构建很尴尬,因此间接重新编译了包含该标头的某些cpp文件。 Hence the error which persisted. 因此错误仍然存​​在。

The effect of the second const was confirmed by a MCVE 第二个const的作用已通过MCVE确认

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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