Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#import in header file or implementation file

Some have the habit of adding header file imports/includes to the header file. Some on the other hand, write a forward declaration in the header file and write the actual #include or #import lines in the implementation file.

Is there a standard practice for this? Which is better and why?

like image 615
Mugunth Avatar asked Nov 19 '10 03:11

Mugunth


2 Answers

Given X.h and X.c, if you #include everything from X.h then clients of "X" that #include <X.h> will also include all those headers, even though some may only be needed in X.c.

X.h should include only what's needed to parse X.h. It should assume no other headers will have been included by the translation unit to ensure that reordering inclusions won't break a client. X.c should include any extras needed for implementation.

This minimises recompilation dependencies. You don't want a change only to the implementation to affect the header and hence trigger a client recompilation. You should simply include directly from X.c.

like image 72
Tony Delroy Avatar answered Sep 29 '22 16:09

Tony Delroy


Including forward references instead of headers is necessary when classes have shallow dependencies. For example:

A.h

#include "B.h"
class A {
   B* pointer;
};

B.h

#include "A.h"
class B {
   A* pointer;
};

Will break at compilation.

A.h

class B;
class A {
   B* pointer;
};

B.h

class A;
class B {
   A* pointer;
};

Will work as each class only needs to know the other class exists at the declaration.

like image 33
Akusete Avatar answered Sep 29 '22 17:09

Akusete