Sobes.tech
Junior

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:

  1. Violation of the One Definition Rule (ODR). When a header file is included by multiple .cpp files, the code contained within it will be defined more than once, leading to a linker error (multiple definition). An exception is inline functions 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
    }
    
  2. 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.

  3. Complication of maintenance and testing. Code scattered across header files becomes less modular. This complicates testing individual components and their independent modification.

  4. 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)
  • inline functions (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).