什么是记录“.h"使用模式的好的参考资料?C中的文件? [英] What is a good reference documenting patterns of use of ".h" files in C?

查看:20
本文介绍了什么是记录“.h"使用模式的好的参考资料?C中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 接口和实现"展示了一些有趣的数据结构使用模式,但我相信还有其他的.

"C Interfaces and Implementations" shows some interesting usage patterns for data structures, but I am sure there are others out there.

http://www.amazon.com/Interfaces-实施-技术-Addison-Wesley-Professional/dp/0201498413

推荐答案

查看戈达德太空飞行中心 (NASA) C 编码标准(在此 URL).它有一些很好且有趣的指南.

Look at the Goddard Space Flight Center (NASA) C coding standard (at this URL). It has some good and interesting guidelines.

我在自己的代码中采用的一个特定准则是,标头应该是自包含的.也就是说,你应该能够写:

One specific guideline, which I've adopted for my own code, is that headers should be self-contained. That is, you should be able to write:

#include "header.h"

并且代码应该正确编译,包括任何其他必要的头文件,不管之前发生了什么.确保这一点的简单方法是在实现源中包含标题——作为第一个标题.如果编译成功,则标头是独立的.如果它不能编译,请修复它以使其编译.当然,这也要求您确保标头是幂等的 - 无论包含的频率如何,都相同.也有一个标准的成语:

and the code should compile correctly, with any other necessary headers included, regardless of what has gone before. The simple way to ensure this is to include the header in the implementation source -- as the first header. If that compiles, the header is self-contained. If it doesn't compile, fix things so that it does. Of course, this also requires you to ensure that headers are idempotent - work the same regardless of how often they are included. There's a standard idiom for that, too:

#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
...operational body of header.h...
#endif /* HEADER_H_INCLUDED */

当然,必须将#define 放在文件的顶部,而不是底部.否则,如果此包含的标头还包含 header.h,那么您最终会陷入无限循环 - 不健康.即使您决定采用以下策略:

It is imperative, of course, to have the #define at the top of the file, not at the bottom. Otherwise, if a header included by this also includes header.h, then you end up with an infinite loop - not healthy. Even if you decide to go with a strategy of:

#ifndef HEADER_H_INCLUDED
#include "header.h"
#endif /* HEADER_H_INCLUDED */

在包含标头的代码中 - 这是推荐的做法 - 在标头本身中包含保护也很重要.

in the code that include the header - a practice which is not recommended - it is important to include the guards in the header itself too.

上面的 GSFC URL 不再有效.您可以在问题的答案中找到更多信息我是否应该在标题中使用 #include,其中还包含对此问题的交叉引用.

The GSFC URL above no longer works. You can find more information in the answers for the question Should I use #include in headers, which also contains a cross-reference to this question.

可以通过 Internet 存档访问和下载引用的 NASA C 编码标准:

The referenced NASA C coding standard can be accessed and downloaded via the Internet archive:

http://web.archive.org/web/20090412090730/http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard

这篇关于什么是记录“.h"使用模式的好的参考资料?C中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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