Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why One Definition Rule, not One Declaration Rule?

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.

like image 296
Chen Li Avatar asked Oct 28 '17 09:10

Chen Li


People also ask

Which one is the correct description of the one definition rule?

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.

What does ODR used mean?

In plain word, odr-used means something(variable or function) is used in a context where the definition of it must be present.


1 Answers

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.

Header included twice

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.

like image 83
Sergey Kalinichenko Avatar answered Nov 07 '22 10:11

Sergey Kalinichenko