Reputation:
Consider:
foo.h:
#include <string>
#include <vector>
class foo
{
std::string a;
std::vector<int> b;
};
bar.h:
#include <string>
#include <vector>
#include "foo.h" // <string> and <vector> included again
class bar
{
std::string c;
std::vector<bool> d;
};
Question: Are the #include
s in foo.h required? I'm aware that header guards will prevent multiple #include
s, but is it okay to omit the #include
s in foo.h?
EDIT: Sorry, what I actually wanted to ask is, is it okay to omit the #include
s in bar.h, since it is already included in foo.h
Upvotes: 0
Views: 1883
Reputation: 20
Like juanchopanza mentioned in his comment, you should check in your first step whether the inludes are really needed in foo.h
and bar.h
. If so, you should keep them. One reason is that if you (or somebody besides you) changes the includes in bar.h
, you must always be aware of this and change your code accordingly. Since the common headers are guarded, you can simply avoid this by writing them in every file where they are needed.
Furthermore, your code is much more understandable. If someone tries getting into your code, he won't see what headers are needed. He'd to look at every single include.
Upvotes: 0
Reputation: 25919
All standard headers have include guards, so, from the perspective of the compiler, it does not matter, whether you include them in both files or only in one.
But it does matter from the perspective of code clarity: someone reading your file will explicitly know, that you actually need string
and vector
for this header to work properly. That simplifies your life as well. Imagine, that a.h
uses b.h
, which uses c.h
, ..., which uses z.h
, which uses <string>
. Would you omit #include <string>
in a.h
as well? Analyzing such code would be a mess.
Also note, that if you omit the includes in bar.h
, you may encounter problems in the future, if you include bar.h
, but do not include <string>
or <vector>
somewhere earlier. Searching for missing includes will be a horror.
TL;DR always include all required headers. The downside is a little bit longer compilation time, but there are a lot more benefits.
Upvotes: 1
Reputation: 154025
Relying on indirect includes is problematic in any non-trivial code base: assuming you don't include <string>
and <vector>
from bar.h
. Now, when foo
changes, e.g., to store the character sequence differently and drops inclusion of <string>
, your header bar.h
breaks. Thus, you create an unnecessary dependency.
In small project these breakages don't matter. In large code bases they can easily become catastrophic. It is also worth noting that changes in class representations actually do work!
Upvotes: 2