Google C ++ programming style guide (1)

Source: Internet
Author: User

Background

Google's open-source projects are mostly developed using C ++. Every C ++ProgramMembers also know that C ++ has many powerful language features, but this powerful will inevitably lead to its complexity, which will makeCodeIt is more prone to bugs, difficult to read and maintain.

The purpose of this Guide is to elaborate on how to write and not write in C ++ encoding to avoid its complexity. These rules allow code to effectively use the C ++ language features while making it easy to manage.

Style, also known as readability, mainly refers to the habit of managing C ++ code. The term style is a bit inappropriate, because these habits are far moreSource codeThe file format is so simple.

One of the ways to make code easy to manage is to enhance code consistency, so that others can understand your code, maintaining a unified programming style means that you can easily deduce the meaning of various symbols based on the pattern matching rule. Creating common and necessary idioms and patterns can make the code easier to understand. Changing the programming style may be a good choice in some cases, but we should still follow the consistency principle, try not to do this.

Another point in this guide is the bloated nature of C ++. C ++ is a giant language that contains a large number of advanced features. In some cases, we may restrict or even prohibit the use of certain features to simplify the code and avoid possible problems, the Guide lists these features and explains why these features are restricted.

Open-source projects developed by Google will comply with the provisions of this Guide.

Note: This guide is not a C ++ tutorial. We assume that you are familiar with C ++.

Header file

Generally, every. CC files (C ++ source files) have a corresponding one. h file (header file), there are some exceptions, such as unit test code and only include main. CC file.

Correct use of header files can greatly improve code readability, file size, and performance.

The following rules will guide you to avoid various troubles when using header files.

 

1. # define protection

All header files should use # define to prevent multiple inclusion. The naming format is <project >_< path >_< file >_h _

To ensure uniqueness, the header file name should be based on the full path of the project's source code tree. For example, the header file Foo/src/BAR/Baz. h In project foo is protected as follows:

# Ifndef foo_bar_baz_h _

# Define foo_bar_baz_h _

...

# Endif // foo_bar_baz_h _

 

2. header file dependency

Use the forward statements to minimize the number of # include in. H files.

When a header file is included and a new dependency is introduced, the code will be re-compiled as long as the header file is modified. If your header file contains other header files, any changes to these header files will also lead to code recompilation that contains your header files. Therefore, we would rather include as few header files as possible, especially those contained in other header files.

Using the pre-declaration can significantly reduce the number of header files to be included. Example: If the class file is used in the header file, but you do not need to access the file declaration, you only need to declare the class file in front of the header file; no # include "file/base/file. H" is required ".

In the header file, how do I use the class Foo without the definition of the category class?

1) Declare the data member type as Foo * or Foo &;

2) The function with the parameter and return value type foo is declared (but not implemented );

3) The type of the static data member can be declared as Foo, because the definition of the static data member is outside the class definition.

On the other hand, if your class is a subclass of Foo or contains non-static data members of the type Foo, you must include the header file.

Sometimes it is more meaningful to use a pointer member (pointer members, if scoped_ptr is better) to replace object members. However, this approach will reduce code readability and execution efficiency. If you only want to include fewer header files, do not replace them.

Of course, the. CC file requires the definition of the class in any way, and naturally contains several header files.

Note: If the Declaration can be relied on, do not rely on the definition.

 

3. inline functions

A function is defined as an inline function only when there are 10 or even fewer rows ).

Definition: After a function is declared as an inline function, the compiler may expand it inline without calling the inline function according to the common function call mechanism.

Advantage: When the function body is small, inline function can make the target code more efficient. For access functions (accessor and mutator) and other short key execution functions.

Disadvantage: Misuse of inline will lead to program slowdown. inline may be the amount of target code or increase or decrease, depending on the size of the function to be inline. Inline short and small access functions usually reduce the amount of code, but inline a large function will dramatically increase the amount of Code if the compiler permits. On a Modern processor, because of the better use of instruction caching, compact code is often executed faster.

Conclusion: A proper processing rule is to avoid inline functions with more than 10 rows. You should be careful with the destructor. The Destructor usually looks longer than its surface because some implicit members and basic class destructor (if any) are called!

Another useful processing rule: inline functions that contain loops or switch statements are not worth the candle unless in most cases these loops or switch statements are never executed.

Importantly, virtual and recursive functions are not necessarily inline functions even if declared as inline functions. Generally, recursive functions should not be declared as inline (note: the expansion of the recursive call stack is not as simple as a loop. For example, the number of recursive layers may be unknown during compilation, most compilers do not support inline recursive functions ). The main reason for inline destructor is that they are defined in the class definition to facilitate or document their behavior.

 

4.-inL. h file

The definition of complex inline functions should be placed in the header file with the suffix-inL. h.

Define inline functions in the header file so that the compiler can expand them inline at the call. However, the implementation code should be fully put into the. CC file. We do not want too much implementation code in the. h file unless it has obvious advantages in readability and efficiency.

If the definitions of inline functions are short and the logic is simple, the implementation code can be placed in. H files. For example, the implementation of the access function is put in the class definition. For the convenience of implementation and call, more complex inline functions can also be placed. in the H file, if you think this will make the header file seem bulky, you can also separate it into a separate-inL. h. In this way, the implementation and class definition are separated. When necessary, the-inL. H of the implementation can be included.

-The inL. h file can also be used for defining function templates to enhance the readability of template definitions.

One thing to note is that-inL. H, like other header files, also requires # define protection.

5. function parameter Ordering)

When defining a function, the parameter order is: the input parameter is in the front, and the output parameter is in the back.

C/C ++ function parameters are divided into two types: input parameters and output parameters. Sometimes input parameters are output (NOTE: When the value is modified ). A value or constant reference (const references) is generally input. The output parameter or input/output parameter is a non-constant pointer (non-const pointers ). When sorting parameters, all input parameters are placed before the output parameters. Do not put the newly added parameter at the end, but before the output parameter.

This is not a rule that must be followed. Mixing input/output parameters (usually class/struct variables) makes it difficult to follow the rules.

 

6. Names and order of files contained

Standardizing the inclusion order improves readability and avoids hidden dependencies (hidden dependencies). Note: hidden dependencies mainly refer to the inclusion of files during compilation. The order is as follows: C library, C ++ library, and other libraries. h. h.

The header files in the project should be arranged in the tree structure of the project source code directory, and the Unix File paths (current directory) and (parent directory) should be avoided ). For example, Google-awesome-Project/src/base/logging. H should be included as follows:

# Include "base/logging. H"

DIR/Foo. CC is mainly used to execute or test the dir2/foo2.h function. Foo. CC contains the following header file order:

Dir2/foo2.h (priority, details are as follows)

C System File

C ++ System File

Other library header files

Header files in this project

This sorting method can effectively reduce hidden dependencies. We hope that each header file can be compiled independently. The simplest implementation method is to include the first. h file in the corresponding. CC file.

DIR/Foo. CC and dir2/foo2.h are usually located in the same directory (such as base/basictypes_unittest.cc and base/basictypes. h), but they can also be located in different directories.

The header files in the same directory are in alphabetical order.

For example, Google-awesome-Project/src/Foo/Internal/fooserver. CC contains the following order:

# Include "foo/public/fooserver. H" // priority

# Include <sys/types. h>

# Include <unistd. h>

# Include

# Include <vector>

# Include "base/basictypes. H"

# Include "base/commandlineflags. H"

# Include "foo/public/bar. H"

 

Translator: English is not very good and translation is not very good. This article mainly mentions some rules for header files, which are summarized as follows:

1. avoiding multiple inclusion is the most basic requirement for programming;

2. The pre-declaration aims to reduce compilation dependencies and prevent the domino effect caused by modifying a header file;

3. Proper Use of inline functions can improve code execution efficiency;

4.-inL. h can improve code readability (usually not used: d );

5. The order of standardized function parameters can improve readability and Maintainability (it has a slight impact on the stack space of function parameters. I used to put the same types together );

6. the name of the contained file is used. and .. although convenient but confusing, the use of a complete project path looks clear and organized, including the order of files in addition to appearance, the most important thing is to reduce hidden dependencies, make each header file compile in the place where "the most need to compile" (corresponding to the source file: d). Someone suggested that the library file should be placed at the end. In this case, the first error is the file in the project, the header file is placed at the beginning of the corresponding source file, which is enough to ensure timely detection of internal errors.

This article from programming entry Network: http://www.bianceng.cn/Programming/cplus/201009/19333.htm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.