The Placement of C Definitions in Header Files: Is It a Common Practice?
In the realm of C programming, the placement of class declarations and definitions has sparked a debate. Traditionally, the norm has been to separate these aspects into include files and *.cpp files, respectively. However, a coworker asserts that current best practice dictates the inclusion of definitions within header files.
To assess the prevalence of this alleged new idiom, let us examine the widespread usage pattern in C development:
Conventional Approach: Separating Declarations and Definitions
Countless C developers adhere to the conventional style, which involves declaring classes in include files (.h) and implementing their definitions in .cpp files. This practice is akin to the separation of specification and body files in Modula-2 and Ada.
Advantages:
Header-Only Definitions: An Alternative
Some instances may justify placing definitions in header files, particularly to enhance compiler optimizations such as inlining. However, adopting this approach comes with drawbacks:
When Header-Only Definitions Are Appropriate
The only scenario where header-only definitions are truly advantageous is when working with templates. Modern C libraries often employ templates extensively, requiring header-only definitions.
Conclusion:
Your coworker's claim that all C declarations should be defined within header files is not supported by common practice. While header-only definitions have their niche applications, the established approach of separating declarations and definitions remains the widely accepted norm.
The above is the detailed content of Should C Class Definitions Be Placed in Header Files?. For more information, please follow other related articles on the PHP Chinese website!