telecom • networking • design

an blog

Rules for managing header file includes in C++

Leave a comment

C++ header file include rulesC++ header file management can be very frustrating:

  • Changing the the order of header files often results in difficult to track compilation errors
  • C++ project compilations take a long time due to complex header file inclusions

Here are a few rules to remedy this:

  • A header file should be included only when a forward declaration would not do the job.
  • The header file should be so designed that the order of header file inclusion is not important.
    • This is achieved by making sure that x.h is the first header file in x.cpp
  • The header file inclusion mechanism should be tolerant to duplicate header file inclusions.

An example of illustrates the header file inclusion rules:

Header file

#ifndef _a_h_included_
#define _a_h_included_
#include "abase.h"
#include "b.h"

// Forward Declarations
class C;
class D;

class A : public ABase
  B m_b;
  C *m_c;
  D *m_d;

  void SetC(C *c);
  C *GetC() const;

  void ModifyD(D *d);

Source file

#include "a.h"
#include "d.h"

void A::SetC(C* c)
  m_c = c;

C* A::GetC() const
  return m_c;

void A::ModifyD(D* d)
  m_d = d;

For details, refer to: C++ Header File Include Rules

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s