您对大型项目的首选 C/C++ 标头策略? [英] Your preferred C/C++ header policy for big projects?

查看:22
本文介绍了您对大型项目的首选 C/C++ 标头策略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理大型 C/C++ 项目时,您是否对源文件或头文件中的 #include 有一些特定规则?

When working on a big C/C++ project, do you have some specific rules regarding the #include within source or header files?

例如,我们可以想象遵循以下两条过度规则之一:

For instance, we can imagine to follow one of these two excessive rules:

    .h 文件中禁止使用
  1. #include;由每个 .c 文件来包含它需要的所有标题
  2. 每个 .h 文件都应包含其所有依赖项,即它应该能够单独编译而不会出现任何错误.
  1. #include are forbidden in .h files; it is up to each .c file to include all the headers it needs
  2. Each .h file should include all its dependancies, i.e. it should be able to compile alone without any error.

我认为任何项目之间都需要权衡取舍,但您的项目是什么?你有更具体的规则吗?或者任何支持任何解决方案的链接?

I suppose there is trade-off in between for any project, but what is yours? Do you have more specific rules? Or any link that argues for any of the solutions?

推荐答案

如果你只在 C 文件中包含 H 文件,那么在 C 文件中包含 H 文件可能会导致编译失败.它可能会失败,因为您可能必须预先包含 20 个其他 H 文件,更糟糕的是,您必须以正确的顺序包含它们.拥有大量 H 文件,从长远来看,该系统最终将成为管理方面的噩梦.您想要做的只是包含一个 H 文件,结果您花了两个小时找出还需要包含哪些其他 H 文件.

If you include H-files exclusively into C-files, then including a H-file into a C-file might cause compilation to fail. It might fail because you may have to include 20 other H-files upfront, and even worse, you have to include them in the right order. With a real lot of H-files, this system ends up to be an administrative nightmare in the long run. All you wanted to do was including one H-file and you ended up spending two hours to find out which other H-files in which order you will need to include as well.

如果一个 H 文件只有在首先包含另一个 H 文件的情况下才能成功包含到 C 文件中,那么第一个 H 文件应该包含第二个 H 文件,依此类推.这样,您可以简单地将每个 H 文件包含到您喜欢的每个 C 文件中,而不必担心这可能会破坏编译.这样你只指定你的直接依赖项,但如果这些依赖项本身也有依赖项,则由它们来指定.

If a H-file can only be successfully included into a C-file in case another H-file is included first, then the first H-file should include the second one and so on. That way you can simply include every H-file into every C-file you like without having to fear that this may break compilation. That way you only specify your direct dependencies, yet if these dependencies themselves also have dependencies, its up to them to specify those.

另一方面,如果没有必要,请不要将 H 文件包含到 H 文件中.hashtable.h 应该只包含使用哈希表实现所需的其他头文件.如果实现本身需要 hashing.h,则将其包含在 hashtable.c 中,而不是 hashtable.h 中,因为只有实现需要它,而不是只想使用最终哈希表的代码.

On the other hand, don't include H-files into H-files if that isn't necessary. hashtable.h should only include other header files that are required to use your hashtable implementation. If the implementation itself needs hashing.h, then include it in hashtable.c, not in hashtable.h, as only the implementation needs it, not the code that only would like to use the final hashtable.

这篇关于您对大型项目的首选 C/C++ 标头策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆