I have read materials below:
https://www.wikiwand.com/en/One_Definition_Rule
http://en.cppreference.com/w/cpp/language/definition
What is the difference between a definition and a declaration?
But still, can't figure out why it is One Definition Rule rather than One Declaration Rule?
I maintain that declaration is a subset of definition, so One Definition Rule is enough.
The One Definition Rule (ODR) is an important rule of the C++ programming language that prescribes that classes/structs and non-inline functions cannot have more than one definition in the entire program and template and types cannot have more than one definition by translation unit.
In plain word, odr-used means something(variable or function) is used in a context where the definition of it must be present.
One declaration rule would be too strict, preventing programs that use the same header more than once from compiling. It would also make it impossible to define data structures with back references.
A simple way to see the first point (using headers) is to consider a program composed of two translation units, A.cpp and B.cpp, which both include <string> header.

Translation units A.cpp and B.cpp are translated independently. By including <string>, both translation units acquire a declaration of std::string.
As for the second point (data structures with back references) consider an example of defining a tree in which each node has a back reference to its parent tree:
// Does not compile
struct tree {
struct node *root;
};
struct node {
struct node *left;
struct node *right;
struct tree *owner;
};
This example would not compile, because node from struct node *tree is undeclared. Switching the order of struct node and struct tree declarations wouldn't help, because then tree from struct tree *owner would be undeclared. The only solution in C and C++ is to introduce a second declaration for either of the two structs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With