Why do we not write code in header files?
sobes.tech AI
Answer from AI
Code in header files (.h or .hpp in C++) is not placed there for the following reasons:
-
Violation of the One Definition Rule (ODR). When a header file is included by multiple
.cppfiles, the code contained within it will be defined more than once, leading to a linker error (multiple definition). An exception isinlinefunctions and class/function templates, which must be defined in every translation unit where they are used.// example.h int g_counter = 0; // Global variable - violates ODR void my_function() { // Function - violates ODR // some code } inline void my_inline_function() { // inline function - exception // some code } template<typename T> void process(T value) { // Template function - exception // some code } -
Increased compilation time. Each time a header file is included, the compiler reprocesses its contents. Placing code in header files increases the workload for the compiler, slowing down the build process, especially in large projects.
-
Complication of maintenance and testing. Code scattered across header files becomes less modular. This complicates testing individual components and their independent modification.
-
Risk of include loops. Incorrect organization of includes with code in header files can lead to cyclic dependencies and compilation issues.
Typically, header files declare:
- Classes (definitions, but not method implementations)
- Function prototypes
- Global variables (using
extern) - Constants
- Class and function templates (full definitions)
inlinefunctions (full definitions)- Data types (
struct,enum,typedef,using) - Namespaces (
namespace)
The implementation code (function bodies, static member definitions, and global variables) is placed in corresponding implementation files (.cpp).