Home > Article > Backend Development > Can You Define Inline Member Functions in .cpp Files? A Look at Circular Includes and Compiler Behavior.
Defining Inline Member Functions in .cpp Files: A Conundrum
While inline member functions are typically placed in headers for direct inclusion during compilation, certain scenarios demand their implementation in .cpp files. One such case involves circular includes, where the implementation of an inline member function must be defined in a .cpp file.
Dilemma of Circular Includes
Consider the following example:
A.h
<code class="cpp">#pragma once #include "B.h" class A { B b; };</code>
B.h
<code class="cpp">#pragma once class A; // forward declaration class B { inline A getA(); };</code>
B.cpp
<code class="cpp">#include "B.h" #include "A.h" inline A B::getA() { return A(); }</code>
In this situation, due to the circular include between A.h and B.h, the implementation of the inline member function getA() needs to be defined in B.cpp. However, this raises a fundamental question:
Will the Compiler Inline getA() Properly?
No. The compiler only inlines a function when its definition is available at the point of use. In the above example, the definition of getA() is not visible when it is called from other .cpp files, leading to an "unresolved external" error during linking.
Significance of Inline Keywords
Only the inline keyword present in the definition outside the class body (in B.cpp in this case) is significant. The inline keyword in the header (in B.h) serves as a declaration, indicating that the implementation will be provided elsewhere.
Alternative Approach to Defining Inline Member Functions in .cpp Files
Currently, there is no alternative method to define inline member functions in .cpp files. The standard requires that their definition be placed in headers for proper inline expansion.
The above is the detailed content of Can You Define Inline Member Functions in .cpp Files? A Look at Circular Includes and Compiler Behavior.. For more information, please follow other related articles on the PHP Chinese website!