简体   繁体   中英

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.

You did define this array inside a namespace, not in a global scope. Add static keyword before array definition and it should work.

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). But const variables defined inside namespace are not static - this is not necessary, since namespace itself limits their visibility. 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

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

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. Hence the error which persisted.

The effect of the second const was confirmed by a MCVE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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