Question

I have a header file that contains the following definition

const std::string error[] = {"a", "b"};

Now I'm including this file in two different translation units and compiling the source codes. Everything works, but why? This is expected to break one definition rule.

Now even more interesting, I'm changing the type

const char* error[] = {"a", "b"};

and here it is, expected error

multiple definition of `error'

It works the same way as for std::string for int, char, short and other integral types. What is this?

Was it helpful?

Solution

const gives namespace-scoped variables internal linkage, that's why it works, effectively the same as

static const std::string error[] = {"a", "b"};

The second one doesn't work because it's not the variable that is const, but the chars it consists of.

OTHER TIPS

Global variables declared const have internal linkage, as if they were also declared static. You can define internal variables with the same name in different translation units, so that's what happens in your first example - each unit that includes the header gets its own copy of the array.

The second example is not const - the pointers point to constant objects, but are themselves mutable. So this array has external linkage, and is subject to the One Definition Rule.

From MSDN

In C, constant values default to external linkage, so they can appear only in source files. In C++, constant values default to internal linkage, which allows them to appear in header files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top