Sobes.tech
Middle

In which situations is it necessary to write code in header files?

sobes.tech AI

Answer from AI

Cases when code is written in header files:

  1. Template functions and classes: The compiler needs to know the entire code of the template for its instantiation when used.

    template <typename T>
    T max(T a, T b) {
        return (a > b) ? a : b;
    }
    
  2. Inline functions: The compiler may replace a function call with its body, which requires the function code to be present at the call site. The inline keyword is just a suggestion to the compiler.

    inline int add(int a, int b) {
        return a + b;
    }
    
  3. Constant variables with internal linkage (static const / constexpr): Such variables are usually defined and initialized directly in the header file.

    static const int MAX_SIZE = 100;
    constexpr double PI = 3.14159;
    
  4. Declarations and definitions of static constant members: For integral types, they can be initialized directly within the class declaration.

    class MyClass {
    public:
        static const int DEFAULT_VALUE = 42;
    };
    
  5. Some types of macros: Although macro usage should be minimized in favor of constexpr, they can be defined in header files for project-wide distribution.

    #define BUFFER_SIZE 1024
    
  6. Small accessor or getter/setter functions: Sometimes, for performance or convenience, small functions can be defined in header files, often with implicit or explicit inline.

    class Point {
    private:
        int x_, y_;
    public:
        int getX() const { return x_; }
        void setX(int x) { x_ = x; }
    };
    

Duplicating function or variable definitions with external linkage in header files leads to linkage errors (One Definition Rule violation), except for the cases listed above.