K.K. Slider
K.K. Slider

Reputation: 77

C++, Should I #include something if I need it *and* something else it includes?

Let's say I have a header file called foo.h, and it includes another header, bar.h.

I also have a header file called xyz.h. It requires foo.h and bar.h, although foo.h and bar.h have nothing to do with each other, so I would feel weird to just include foo.h (which still compiles since it includes bar.h...

So, foo.h includes bar.h, bar.h doesn't include foo.h, but xyz.h does include foo.h and bar.h. Is this bad practice? Is there any reason why I shouldn't? Why am I able to do this?

Upvotes: 1

Views: 168

Answers (1)

Nikita
Nikita

Reputation: 6427

Each header should be self-contained. It should include all other headers it needs and have include guards.

Suppose that the header was not self contained. Then if you wish to use that header in a different client, then the new client wouldn't even compile unless you found and pulled the need other headers.

There are also can be rare case when header file can be not self-contained, e.g. checks Google's code style for details.

Most of compilers support options for include dependency investigation. These options and other tools are discussed in this question.

Upvotes: 2

Related Questions