Reputation: 9292
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.
Upvotes: 1
Views: 1029
Reputation: 9292
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
Upvotes: 0
Reputation: 238351
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.
Upvotes: 1
Reputation: 446
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.
Upvotes: 3