c++ - 命名空间菜鸟问题 : two cpp files sharing the same namespace have the same variable

标签 c++ namespaces

命名空间菜鸟问题 我在同一个二进制文件中有两个文件。

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

//class2.cpp

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

它们没有在头文件中声明。 他们不会碰撞吗? 我尝试编译一下,果然可以编译。 我应该将它们放入未命名的命名空间,但即使我不这样做,它似乎仍然能够编译。 这是为什么

编辑:实际上包含这两个文件是为了构建相同的二进制文件。

最佳答案

这是因为const意味着internal linkage 。如果将 A::k1 定义为非 const,您将收到有关重复符号的预期错误。

关于c++ - 命名空间菜鸟问题 : two cpp files sharing the same namespace have the same variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62255803/

相关文章:

C++:不同命名空间中的多个运算符定义

Python + lxml : how to find the namespace of a tag?

c# - Azure 服务总线配对命名空间 - 模拟故障转移

c++ - 面向对象的 C++ win32?

c++ - FFMPEG 库 - 将原始图像转码为 h264 流,输出文件不包含 pts 和 dts 信息

xml - 如何获取所有已使用命名空间的列表?

php - 相同的功能,不同的代码——重构一团糟

c++ - 编译 IOS 应用程序时出现库问题

c++ - 初始化列表中的对象初始化问题

c++ - 在 C++ 中创建自定义比较器