namespace noob questions: two cpp files sharing the same namespace have the same variable

Viewed 99

namespace noob questions I have two files in the same binary.

// class1.cpp
namespace A {
 const std::string k1 = "abc";
}

// class2.cpp

namespace A {
 const std::string k1 = "bcd";
}

They are not declared in header file. Won't they collide? I tried to compile and it can compile. I should put them to unnamed namespace but even if I don't, it still seems to be able to compile. Why is that

Edit: Those two files are actually included to build the same binary.

1 Answers

It is because const implies internal linkage. You will get the expected error about duplicate symbols if you defined A::k1 as non const.

Related