0

A similar issue has already been discussed (C/C++ include header file order), but this thread makes no mention of forward declarations. If I summarize what I've read online so far:

  1. Everyone agrees that the corresponding header for the .cpp file should go first. This ensures that the header files has everything it needs.

  2. Beyond that, there seems to be no consensus. The Google guidelines (https://google.github.io/styleguide/cppguide.html) suggest including headers from system -> other libs -> project. Many people on SO suggest the exact opposite. It seems to be a matter of personal preferences.

Regarding forward declarations, is there any reason to add them before/after the include headers? I don't see why it would matter (Is a class declaration allowed after a class definition?), but maybe I am missing something.

Touloudou
  • 2,079
  • 1
  • 17
  • 28
  • 4
    Most of the time the order should not matter. I'm voting to close this as opinion based. – super May 29 '19 at 16:01
  • 1
    you should write your headers such that the order of includes does not matter. If code breaks because you swap two includes then you did something wrong – 463035818_is_not_an_ai May 29 '19 at 16:18
  • I am asking this question precisely because I want to know if this is purely opinion-based, or if there is something more than I need to be aware of. – Touloudou May 29 '19 at 16:38
  • if you've a spinning disk, you could work out which sectors they're all on - and then include them in order to minimise seeking times.... The time saved compared to that of buying a solid state disk or just not doing it and suffering the build time increase makes it well worth it. I do it for all my projects. – UKMonkey May 29 '19 at 17:25

1 Answers1

1

I think this is one of those questions that has no one right answer.

The way I think of it (and its by no means the absolute answer) is from an encapsulation point of view and I tend to do the opposite of the google guidelines for this reason:

  • If you include your project headers first you are less likley to hit issues where your header relies on some system include that went before it because you will just get a compile error... so therefore I find you see issues faster by putting the system includes last.

  • Same thing for the forward declarations - if you need them and they are not provided by a header - then add them after the includes because the headers should not need them (otherwise it would be in the header) and so you only declare it as/when you need it...

That is more-or-less my reasoning - but as I say, if your headers are designed correctly then you could do it either way...

code_fodder
  • 15,263
  • 17
  • 90
  • 167