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

Why Must Inline Function Definitions in C Reside in Header Files?

DDD
Release: 2024-12-08 12:47:13
Original
153 people have browsed it

Why Must Inline Function Definitions in C   Reside in Header Files?

Understanding the Placement Requirement for Inline Function Definitions in Header Files

In C , an inline function is one that is intended to be expanded inline at the point of its call, rather than compiled into a separate function call. While the declaration of a class member function as inline is not necessary, its implementation must be defined inline. This raises the question of why the inline implementation must reside in the header file.

To comprehend this requirement, we must delve into the concept of the one definition rule (ODR) for inline functions. The ODR dictates that an inline function can only have one definitive definition across all translation units that utilize it. This means that if an inline function is defined in multiple source files, their definitions must be identical.

Compliance with the ODR is crucial when working with inline functions. If the definitions are not identical, the linker will encounter unresolved external symbol errors, as illustrated in the example provided in the question.

The simplest approach to guarantee ODR compliance is to define the inline function in a header file. By including the header file in every source file that uses the function, identical definitions are automatically enforced.

However, it's important to note that an inline function definition does not have to reside in a header file. It's possible to define them within a single source file as long as certain conditions are met. Firstly, the function should not be declared inline. A non-inline function does not imply that the compiler cannot perform inline optimization.

The decision of whether to declare a function inline or not should be made based on which version of the ODR best suits your requirements. Adding inline without considering the resulting limitations may not always be the most appropriate choice.

The above is the detailed content of Why Must Inline Function Definitions in C Reside in Header Files?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template