C Inline Member Function in .cpp File: A Dilemma and Resolution
In C , inline member functions are typically declared in header files for efficiency reasons. However, certain scenarios may necessitate implementing the function in a .cpp file. Let's delve into such a situation:
Consider the following scenario with circular dependencies:
A.h
<code class="cpp">#pragma once #include "B.h" class A { B b; };</code>
B.h
<code class="cpp">#pragma once class A; class B { inline A getA(); };</code>
To break the circular dependency, the implementation of getA needs to be placed in B.cpp:
B.cpp
<code class="cpp">#include "B.h" #include "A.h" inline A B::getA() { return A(); }</code>
The Dilemma
Does the placement of the inline keyword in both the header and the .cpp file affect the function's inlining?
Resolution
Unfortunately, despite the inline keyword in the .cpp file, the compiler will not inline getA unless it is used within B.cpp itself. This is because the compiler requires the definition of the inline function whenever it is encountered. Typically, placing the function in a header file ensures this availability.
Best Practice
As per C FAQ, it is imperative to define inline functions in header files. Placing them in .cpp files can lead to unresolved external errors.
Alternative Solution
The provided scenario does not suggest an alternative solution to placing the inline function in a .cpp file.
The above is the detailed content of Can Inline Member Functions Be Defined in a .cpp File and Still Be Inlined?. For more information, please follow other related articles on the PHP Chinese website!