to myself 的分类学习日志

做自己想做的事
posts - 232, comments - 6, trackbacks - 0, articles - 0

编码风格

Posted on 2010-08-28 20:59 kongkongzi 阅读(163) 评论(0)  编辑 收藏 引用 所属分类: c++ programming
 

文件包含的名字和顺序

请使用以下标准顺序以保证可读性,并且避免隐藏的依赖:C库,C++库,其他库的.h,你的项目的.h

所有项目的头文件应作为项目源文件目录的后代列出,不要使用UNIX中的目录快捷方式 . (当前目录)和 .. (父目录)。

举个例子,google-awesome-project/src/base/logging.h应该以#include "base/logging.h"的格式包含。

dir/foo.cc中,该文件的主要目的是实现或者测试在dir2/foo2.h中的东西,文件包含应按照如下排序:

1.    dir2/foo2.h (首选位置(preferred location) — 请见下面的详细说明).

2.    C system files.

3.    C++ system files.

4.    Other libraries' .h files.

5.    Your project's .h files.

首选的排序(preferred ordering,译者注:在以上例子中为dir2/foo2.h )降低了隐藏的依赖。我们希望每个头文件能够自我编译。最简单的方式就是确保它们中的每一个都在某个.cc文件中是第一个被#include的。

dir/foo.cc and dir2/foo2.h通常在同一目录下(比 base/basictypes_unittest.cc and base/basictypes.h), 但也可能在不同的目录下。

在每个部分(section)中,根据字母顺序排列是不错的方式。

举个例子,google-awesome-project/src/foo/internal/fooserver.cc 的文件包含顺 序可能是这样:

1
2
3
4
5
6
7
8
9
10

#include "foo/public/fooserver.h" // 首选位置
#include <sys/types.h>
#include <unistd.h>

#include <hash_map>
#include <vector>

#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "foo/public/bar.h"



参考:
1, Google C++ Style Guide:http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
2, Google C++ 风格指南 - 中文版:http://yangyubo.com/google-cpp-styleguide/