问题描述
" C接口和实现"显示了一些有趣的数据结构用法模式,但我敢肯定还有其他.
- 实施技术 - addison-wesley专业/DP/0201498413
推荐答案
查看Goddard太空飞行中心(NASA)C编码标准(在此 url ).它有一些良好而有趣的指南.
我为自己的代码采用的一个特定指南是,标题应该是独立的.也就是说,您应该能够写:
#include "header.h"
和代码应正确编译,包括其他任何必要的标头,无论以前发生了什么.确保这是将标题包括在实现源中的简单方法 - 作为第一个标题.如果汇编,则标题是独立的.如果没有编译,请修复事物,以便这样做.当然,这也需要您确保标题具有智力 - 无论将其包括在内的频率都相同.也有一个标准的成语:
#ifndef HEADER_H_INCLUDED #define HEADER_H_INCLUDED ...operational body of header.h... #endif /* HEADER_H_INCLUDED */
当然,必须将#define放在文件顶部,而不是底部.否则,如果此包含的标头还包括标题.即使您决定采用以下策略:
#ifndef HEADER_H_INCLUDED #include "header.h" #endif /* HEADER_H_INCLUDED */
在包含标题的代码中 - 一种不建议的练习 - 也很重要的是,也要在标题本身中包括后卫.
更新2011-05-01
上面的GSFC URL不再起作用.您可以在问题的答案中找到更多信息我应该在标题中使用#include ,还包含对这个问题的交叉引用.
更新2012-03-24
可以通过Internet存档访问和下载引用的NASA C编码标准:
其他推荐答案 makeheaders 是一种有趣的方法:使用一种工具来生成标头的工具. Makeheaders用于D. R. Hipp的 cvstrac 和化石. 您可能想看看约翰·拉科斯(John Lakos)的大规模C ++软件设计.其他推荐答案
问题描述
"C Interfaces and Implementations" shows some interesting usage patterns for data structures, but I am sure there are others out there.
推荐答案
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 */
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.
Update 2011-05-01
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.
Update 2012-03-24
The referenced NASA C coding standard can be accessed and downloaded via the Internet archive:
其他推荐答案
Makeheaders is an interesting approach: use a tool to generate the headers. Makeheaders is used in D. R. Hipp's cvstrac and fossil.
其他推荐答案
You might want to take a look at Large-Scale C++ Software Design by John Lakos.