2

What is the right order between the following examples:

A, system header go ahead

    #include <stdio.h>
    #include "user-define.h"

B, user header go ahead

    #include "user-define.h"
    #include <stdio.h>
zhengfish
  • 113
  • 12

2 Answers2

3

Properly written user headers should include whatever headers they need, because the user of a header shouldn't have to know which headers need to be included beforehand. This follows from the principle of encapsulation.

For the same reason, properly written user headers should be protected against multiple inclusions. Imagine that the main program includes A and B and that A includes C, then it should be possible to modify B so that it too includes C without changing any other file.

With properly written user headers then, the order of inclusion doesn't matter. It is purely a matter of preference. Personally I like to put system headers first, library headers second, and user headers third but you can do what you want.

1

When it comes to header files, I have used the first approach exclusively as long as I can remember.

When it comes to source files, I use the same approach unless there is a header file that corresponds to a source file. In the case, I #include the particular header file first.

Let's say I have A.h that declares a class or some functions and A.cc implements them. In that case, I use:

A.c:

#include "A.h"

// Standard includes

// User includes

This is useful in weeding out any missing forward declarations or standard include files that are necessary to make A.h a reusable header file without worrying about what else must be #included to be able to use #include "A.h" in other source files.

R Sahu
  • 204,454
  • 14
  • 159
  • 270