Home >Backend Development >C++ >Why Must Inline Function Definitions Be Placed in Header Files?

Why Must Inline Function Definitions Be Placed in Header Files?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 05:05:09540browse

Why Must Inline Function Definitions Be Placed in Header Files?

Why Inline Function Definitions Reside in Header Files

In C , declaring class member functions as inline requires their implementation within the header file. This requirement arises from the "one definition rule (ODR)" for inline functions, which mandates that an identical definition exist in all translation units using the function.

The simplest method of ensuring ODR adherence is to include the definition in a header file accessible to all translation units. By doing so, the compiler can locate and use the same definition in all instances where the function is called.

Attempting to place the inline definition in a .cpp file results in an unresolved external symbol error. This occurs because the compiler cannot locate the function definition in the translation unit where it is called.

To reiterate, inline function definitions within header files facilitate ODR compliance by ensuring that an identical definition exists in every translation unit. However, it is important to note that declaring a function inline does not guarantee its inlining by the compiler.

The above is the detailed content of Why Must Inline Function Definitions Be Placed in Header Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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