Google C++ Style Guide
来源:互联网 发布:天刀捏脸的数据am 编辑:程序博客网 时间:2024/05/20 03:08
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#The__define_Guard
Google C++ Style Guide
Revision 3.180
Benjy WeinbergerCraig Silverstein
Gregory Eitzmann
Mark Mentovai
Tashana Landray
Each style point has a summary for which additional information is available by toggling the accompanying arrow button that looks this way:
. You may toggle all summaries with the big arrow button:Important Note
Displaying Hidden Details in this Guide
Background
C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain.
The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively.
Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting.
One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency.
Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted.
Open-source projects developed by Google conform to the requirements in this guide.
Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.
Header Files
In general, every .cc
file should have an associated .h
file. There are some common exceptions, such as unittests and small .cc
files containing just a main()
function.
Correct use of header files can make a huge difference to the readability, size and performance of your code.
The following rules will guide you through the various pitfalls of using header files.
The #define Guard
#define
guards to prevent multiple inclusion. The format of the symbol name should be <PROJECT>_<PATH>_<FILE>_H_
. Header File Dependencies
#include
when a forward declaration would suffice. Inline Functions
Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism.
Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions.
Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache.
Decision:
A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls!
Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed).
It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators.
The -inl.h Files
-inl.h
suffix to define complex inline functions when needed. Function Parameter Ordering
Names and Order of Includes
.h
, your project's .h
. Scoping
Namespaces
.cc
files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive. Nested Classes
Nonmember, Static Member, and Global Functions
Local Variables
Static and Global Variables
Classes
Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class.Doing Work in Constructors
Init()
method. Default Constructors
Explicit Constructors
explicit
for constructors with one argument. Copy Constructors
DISALLOW_COPY_AND_ASSIGN
. Structs vs. Classes
struct
only for passive objects that carry data; everything else is a class
. Inheritance
public
. Multiple Inheritance
Interface
suffix. Interfaces
Interface
suffix. Operator Overloading
Access Control
private
, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected
when using Google Test). Typically a variable would be called foo_
and the accessor function foo()
. You may also want a mutator function set_foo()
. Exception: static const
data members (typically called kFoo
) need not be private
. Declaration Order
public:
before private:
, methods before data members (variables), etc. Write Short Functions
Google-Specific Magic
There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere.
Smart Pointers
scoped_ptr
is great. You should only use std::tr1::shared_ptr
under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr
. cpplint
cpplint.py
to detect style errors. Other C++ Features
Reference Arguments
const
. Function Overloading
Default Arguments
Variable-Length Arrays and alloca()
alloca()
. Friends
friend
classes and functions, within reason. Exceptions
Run-Time Type Information (RTTI)
Casting
static_cast<>()
. Do not use other cast formats like int y = (int)x;
or int y = int(x);
. Streams
Preincrement and Predecrement
++i
) of the increment and decrement operators with iterators and other template objects. Use of const
const
whenever it makes sense to do so. Integer Types
int
. If a program needs a variable of a different size, use a precise-width integer type from <stdint.h>
, such as int16_t
. 64-bit Portability
Preprocessor Macros
const
variables to macros. 0 and NULL
0
for integers, 0.0
for reals, NULL
for pointers, and '/0'
for chars. sizeof
sizeof(varname)
instead of sizeof(type)
whenever possible. Boost
C++0x
Naming
The most important consistency rules are those that govern naming. The style of a name immediately informs us what sort of thing the named entity is: a type, a variable, a function, a constant, a macro, etc., without requiring us to search for the declaration of that entity. The pattern-matching engine in our brains relies a great deal on these naming rules.
Naming rules are pretty arbitrary, but we feel that consistency is more important than individual preferences in this area, so regardless of whether you find them sensible or not, the rules are the rules.
General Naming Rules
File Names
_
) or dashes (-
). Follow the convention that your project uses. If there is no consistent local pattern to follow, prefer "_". Type Names
MyExcitingClass
, MyExcitingEnum
. Variable Names
my_exciting_local_variable
, my_exciting_member_variable_
. Constant Names
k
followed by mixed case: kDaysInAWeek
. Function Names
MyExcitingFunction()
, MyExcitingMethod()
, my_exciting_member_variable()
, set_my_exciting_member_variable()
. Namespace Names
google_awesome_project
. Enumerator Names
kEnumName
or ENUM_NAME
. Macro Names
MY_MACRO_THAT_SCARES_SMALL_CHILDREN
. Exceptions to Naming Rules
Comments
Though a pain to write, comments are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names that you must then explain through comments.
When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous — the next one may be you!
Comment Style
//
or /* */
syntax, as long as you are consistent. File Comments
Class Comments
Function Comments
Variable Comments
Implementation Comments
Punctuation, Spelling and Grammar
TODO Comments
TODO
comments for code that is temporary, a short-term solution, or good-enough but not perfect. Deprecation Comments
DEPRECATED
comments. Formatting
Coding style and formatting are pretty arbitrary, but a project is much easier to follow if everyone uses the same style. Individuals may not agree with every aspect of the formatting rules, and some of the rules may take some getting used to, but it is important that all project contributors follow the style rules so that they can all read and understand everyone's code easily.
To help you format code correctly, we've created a settings file for emacs.
Line Length
Non-ASCII Characters
Spaces vs. Tabs
Function Declarations and Definitions
Function Calls
Conditionals
else
keyword belongs on a new line. Loops and Switch Statements
{}
or continue
. Pointer and Reference Expressions
Boolean Expressions
Return Values
return
expression with parentheses. Variable and Array Initialization
=
or ()
. Preprocessor Directives
Class Format
public
, protected
and private
order, each indented one space. Constructor Initializer Lists
Namespace Formatting
Horizontal Whitespace
Vertical Whitespace
Exceptions to the Rules
The coding conventions described above are mandatory. However, like all good rules, these sometimes have exceptions, which we discuss here.
Existing Non-conformant Code
Windows Code
Parting Words
Use common sense and BE CONSISTENT.
If you are editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around their if
clauses, you should, too. If their comments have little boxes of stars around them, make your comments have little boxes of stars around them too.
The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you are saying, rather than on how you are saying it. We present global style rules here so people know the vocabulary. But local style is also important. If code you add to a file looks drastically different from the existing code around it, the discontinuity throws readers out of their rhythm when they go to read it. Try to avoid this.
OK, enough writing about writing code; the code itself is much more interesting. Have fun!
Revision 3.180
Benjy WeinbergerCraig Silverstein
Gregory Eitzmann
Mark Mentovai
Tashana Landray
- Google Objective-C Style Guide
- Google Objective-C Style Guide 中文版
- Google Objective-C Style Guide 中文版
- Google Objective-C Style Guide 中文版
- Google Objective-C Style Guide 中文版
- Google Objective-C Style Guide 中文版
- Google Objective-C Style Guide 中文版
- Google Objective-C Style Guide 中文版
- Google C++ Style Guide
- Google C++ Style Guide
- Google C++ style guide
- Google c++ style guide
- Google C++ Style Guide
- Google C++ Style Guide
- Google C++ Style Guide
- Google C++ Style Guide
- Google C++ Style Guide
- Google C++ Style Guide
- Linux系统中/dev/mtd与/dev/mtdblock的区别
- VC _T的用途
- pb中mfcdec filter 编译输出信息分析
- ^_^
- !!!
- Google C++ Style Guide
- root moto ME525 (Defy)并使用tcpdump抓包
- 一个好用的 命令行音乐播放器moc
- iPhone的等待图标
- 深入了解window.location
- 浅析计算机网络应用安全问题与策略研究
- 动态链接库与静态链接库
- 判断指定日期是星期几(delphi编程实现)
- Watir VS Selenium