0

There was a highly rated response in a question about header ordering with the following suggestion:

Good practice: every .h file should have a .cpp that includes that .h first before anything else. This proves that any .h file can be put first.

Even if the header requires no implementation, you make a .cpp that just includes that .h file and nothing else.

Personally I've never had a problem with include ordering for headers that don't have a corresponding cpp file. What kinds of problems does this best practice prevent?

Community
  • 1
  • 1
Kai
  • 2,482
  • 1
  • 19
  • 21
  • this could prevent a problem if two headers files have the same named definition in them (for whatever reason) or if one header includes another and the header doesn't have the `#ifndef HEADER_H #define HEADER_H` in it. – twain249 Apr 06 '12 at 17:07
  • This practice ensures that each header has all of it's dependencies listed. It's common for headers to use `std::vector` but not include ``, and never notice, since there's always a header included before them that _did_ include ``. I've seen it a lot, especially on this site. – Mooing Duck Apr 06 '12 at 17:34

2 Answers2

3
  1. The header file should compile on itself. ie. for testing make a .cpp file that just includes the header file.
  2. The header file should be guarded by the pre-processor. if #ifndef etc...

Both these will ensure that the order will not matter.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • These seem like the important things to me as well. It sounds like the "one cpp for every header" practice is redundant if you're already following cpp best practices. – Kai Apr 06 '12 at 17:15
0

One problem it solves is allowing the .h file to be linted (at least by my lint tools). Without a .cpp doing an include of an .h my template code gets skipped.

Tod
  • 8,192
  • 5
  • 52
  • 93