Home > Backend Development > C++ > What is ODR-Use in C and When is a Definition Required?

What is ODR-Use in C and When is a Definition Required?

Patricia Arquette
Release: 2024-12-06 12:05:15
Original
706 people have browsed it

What is ODR-Use in C   and When is a Definition Required?

Understanding "odr-use" in C

In C , the concept of "one definition rule" (ODR) ensures that for each entity declared in multiple compilation units, there exists only one definition. However, determining when a definition is necessary can be confusing. The term "odr-use" comes into play in this context.

According to the C Standard, a variable or function is odr-used:

  • If its name appears in a potentially-evaluated expression and is not an object suitable for constant expression evaluation.
  • In the case of a non-overloaded function, if its name appears in a potentially-evaluated expression or in a set of candidate functions selected by overload resolution.

This definition is a bit abstract, so let's simplify it. Odr-use essentially means that an entity is used in such a way that it must be defined somewhere in the program. This includes actual usage, such as calling a function or accessing a variable, as well as potential usage, such as being a candidate for overload resolution.

In the case of class template member functions, they are only instantiated (and therefore defined) if they are odr-used. This means that they must be called, or the class itself must be instantiated with that member function being virtual.

The standard relies on this principle to prevent unnecessary instantiation. For example, the std::list::sort function requires operator< on its elements. By declaring the list with an element type that doesn't support operator<, as long as sort is not called, the member function will not be instantiated.

Understanding odr-use is crucial for avoiding errors related to missing definitions and multiple definitions in multiple compilation units. By following these rules, programmers can write robust and maintainable C code.

The above is the detailed content of What is ODR-Use in C and When is a Definition Required?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template