开发者

#import in header file or implementation file

Some have the habit of adding header file imports/includes to the header file. Some on the other hand, write a forward declaration in the header file and write the actual #include or #import lines in the implementation file.

Is there a sta开发者_开发知识库ndard practice for this? Which is better and why?


Given X.h and X.c, if you #include everything from X.h then clients of "X" that #include <X.h> will also include all those headers, even though some may only be needed in X.c.

X.h should include only what's needed to parse X.h. It should assume no other headers will have been included by the translation unit to ensure that reordering inclusions won't break a client. X.c should include any extras needed for implementation.

This minimises recompilation dependencies. You don't want a change only to the implementation to affect the header and hence trigger a client recompilation. You should simply include directly from X.c.


Including forward references instead of headers is necessary when classes have shallow dependencies. For example:

A.h

#include "B.h"
class A {
   B* pointer;
};

B.h

#include "A.h"
class B {
   A* pointer;
};

Will break at compilation.

A.h

class B;
class A {
   B* pointer;
};

B.h

class A;
class B {
   A* pointer;
};

Will work as each class only needs to know the other class exists at the declaration.


I write my imports in header files, so that every implementation file has only one inclusion directive. This also has the advantage of hiding dependencies from the user of the module's code.

However, that same hiding has a disadvantage: your module's user may be importing all kinds of other headers included in your header that he may not need at all. From that point of view, it's better to have the inclusion directives in the implementation file, even if it means manually resolving dependencies, because it leads to lighter code.

I don't think there's a single answer. Considering the reasons I gave, I prefer the first approach, I think it leads to cleaner code (albeit heavier and possibly with unnecessary imports).

I don't remember who I'm quoting (and thus the phrase is not exact), but I always remember reading: "programs are written for human beings to read, and ocasionally for computers to execute". I don't particularly care if there are a few kilobytes of code the user of my module won't need, as long as he can cleanly, easily import it and use it with a single directive.

Again, I think it's a matter of taste, unless there's something I failed to consider. Comments are more than welcome in that case!

Cheers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜