C++ 对一个定义规则的困惑

C++ confusion about one definition rule

我在读 One Definition Rule。它说:

if one .cpp file defines struct S { int x; }; and the other .cpp file defines struct S { int y; };, the behavior of the program that links them together is undefined. This is usually resolved with unnamed namespaces.

我不明白为什么以及它是如何未定义的?有人会向我解释这背后的真正原因吗?它是如何用未命名的命名空间解析的?

正如它所说的那样。您定义了相同的 class S 两次,但定义不同。该语言的创造者已声明你不应该这样做。原因是允许它显然是荒谬的,并且会破坏翻译单元之间的兼容性。 "right" 是哪个定义?你的编译器应该使用哪个?

未命名的命名空间导致两个定义实际上定义了 不同的 classes S,它们被正确地命名为类似于 my-anonymous-namespace-1::Smy-anonymous-namespace-2::S,尽管您永远不能那样引用它们,因为命名空间是匿名的。