Google open-source project Style Guide

Source: Internet
Author: User
Http://zh-google-styleguide.readthedocs.org/en/latest/google-cpp-styleguide/naming/ Among them, the blue font is my own naming style, and it will be convenient later.

File: All lowercase letters, which can contain underscores (_), for example, my_useful_class;

Type (class, struct, type definition typedef, enumeration): the first letter of each word is written up; for example, myexcitingclass;

Variable/struct: lower case, which can contain underscores, for example, my_local_varible;

Class member variables: lower case, can contain underscores, and end with the following line; for example, my_local_varible _;

Function: lowercase for the first word, followed by an uppercase letter for each word; for example, addtableentry ();

Constant: starts with K, followed by the first letter of each word; for example, kdaysinaweek;

Global variable: Start with G _, for example, g_my_exciting;

6. Naming Conventions

The most important consistency rule is naming management. The naming style quickly learns what the name represents: type? Variable? Function? Constant? Macro ...? The pattern matching engine in our brain can process these naming rules very reliably.

Naming rules are random, but they are more consistent than naming rules by personal preferences. Therefore, no matter what you think, rules are always rules.

6.1. General naming rules

Tip

Function Name, variable name, file name should be descriptive; Do not over abbreviation. Type and variable should be a noun, function name can use "imperative" verb.

How to name:
Give descriptive names as much as possible. Do not save row space, so that others can quickly understand your code more important. Good naming style:
int num_errors;                  // Good.int num_completed_connections;   // Good.
Bad naming uses vague abbreviations or random characters:
int n;                           // Bad - meaningless.int nerr;                        // Bad - ambiguous abbreviation.int n_comp_conns;                // Bad - ambiguous abbreviation.

Type and variable names are generally nouns: for exampleFileopener,Num_errors.

Function names are usually Directive (specifically, they should be commands), suchOpenfile (),Set_num_errors (). The value function is a special case (inFunction NameThe name of the function and the variable to be taken are the same.

Abbreviation:
Do not use this abbreviation unless it is widely used elsewhere. For example:
// Good // These show proper names with no abbreviations.int num_dns_connections; // most people know what "DNS" means. Int price_count_reader; // OK, price count. It makes sense.

Warning

// Bad!// Abbreviations can be confusing or ambiguous outside a small group.int wgc_connections;  // Only your group knows what this stands for.int pc_reader;        // Lots of things can be abbreviated "pc".
Never omit the abbreviation of a letter:
int error_count;  // Good.int error_cnt;    // Bad.
6.2. File Name

Tip

The file name must be in lowercase and can contain underscores (_) Or hyphen (-). Follow the project conventions.

Acceptable File naming:

my_useful_class.ccmy-useful-class.ccmyusefulclass.cc

The C ++ file must start. CCEnd with the header file. HEnd.

Do not use an existing/Usr/includeFile Name (yospaly Note: that is, the compiler searches for the path of the system header file), as shown inDB. h.

Generally, we should try to make the file name clearer.Http_server_logs.hRatioLogs. hBetter. when defining a class, the file name usually appears in pairs, as shown in figureFoo_bar.hAndFoo_bar.cc, Corresponding to the classFoobar.

Inline functions must be placed in. HFile. If the inline function is short, put it directly. H. If the code is long, you can put it in-InL. hAt the end of the file. For classes that contain a large number of Inline code, you can use three files:

url_table.h      // The class declaration.url_table.cc     // The class definition.url_table-inl.h  // Inline functions that include lots of code.

Reference-InL. h fileSection 1.

6.3. type naming

Tip

The first letter of each word of a type name is uppercase and does not contain underscores:Myexcitingclass,Myexcitingenum.

All types-class, struct, type definition ( Typedef), Enumeration -- all use the same conventions. For example:
// classes and structsclass UrlTable { ...class UrlTableTester { ...struct UrlTableProperties { ...// typedefstypedef hash_map<UrlTableProperties *, string> PropertiesMap;// enumsenum UrlTableErrors { ...
6.4. variable naming

Tip

All variable names are in lowercase, and words are connected by underscores. The member variables of the class end with an underscore, for example:

my_exciting_local_variablemy_exciting_member_variable_
Common variable name:

Example:

string table_name;  // OK - uses underscore.string tablename;   // OK - all lowercase.

Warning

string tableName;   // Bad - mixed case.
Struct variable:
The data member of a struct can be the same as a common variable without being underlined like a class:
struct UrlTableProperties {    string name;    int num_entries;}

Struct and class discussion referenceStruct vs. ClassSection 1.

Global variables:
There are no special requirements for global variables. It is good to use less, but if you want to use it, you can use G _Or other signs as the prefix to better differentiate local variables.
6.5. Constant naming

Tip

AddK: Kdaysinaweek.

All compilation times, whether local, global or class, are slightly different from other variables. KWords Starting with an upper-case letter ::
Const int kdaysinaweek = 7;
6.6. Function Name

Tip

Common functions use a mix of upper and lower cases. Values and value-setting functions must match the variable name:Myexcitingfunction (),Myexcitingmethod (),My_exciting_member_variable (),Set_my_exciting_member_variable ().

Common functions:

The first letter of each word in the function name is in upper case with no underline: (I select the first letter in lower case and the name is partitioned)

AddTableEntry()DeleteUrl()
Value and value setting functions:
The value and value setting function must match the name of the accessed variable. Here we extract a class, Num_entries _Is the instance variable of this class:
class MyClass {    public:        ...        int num_entries() const { return num_entries_; }        void set_num_entries(int num_entries) { num_entries_ = num_entries; }    private:        int num_entries_;};

Other very short inline function names can also use lower-case letters. For example, if you call such a function in a loop, you do not even need to cache the return value. The lower-case name is acceptable.

6.7. namespace name

Tip

The namespace is named in lowercase letters and is based on the project name and directory structure:Google_awesome_project.

For more information about namespaces and how to name them, seeNamespaceSection 1.

6.8. Enumeration naming

Tip

The enumerated name should beConstantOrMacroConsistent:KenumnameOrEnum_name.

Separate enumeration values should be prioritized ConstantBut MacroYou can also use the. Enumeration name. Urltableerrors(And Alternateurltableerrors) Is the type, so it must be case-insensitive.
enum UrlTableErrors {    kOK = 0,    kErrorOutOfMemory,    kErrorMalformedInput,};enum AlternateUrlTableErrors {    OK = 0,    OUT_OF_MEMORY = 1,    MALFORMED_INPUT = 2,};

We always recommend that you useMacro. The name conflict between enumeration values and macros directly causes many problems. therefore, the constant style naming method is preferred here. the new Code should give priority to the constant style. however, the old Code does not need to switch to the constant style unless the macro style does cause compilation problems.

6.9. Macro naming

Tip

You are not planningUse macrosRight? If you must use it, name it like this:My_macro_that_scares_small_children.

ReferencePreprocessing macro <Preprocessor-macros>; UsuallyNoUse macros. If you have to use them, use underscores (_) to name them in uppercase like enumeration:

#define ROUND(x) ...#define PI_ROUNDED 3.0
6.10. Special Cases of naming rules

Tip

If the named object is similar to the existing C/C ++ object, refer to the existing naming policy.

Bigopen ():
Function Name, refer Open ()Format
Uint:
Typedef
Bigpos:
StructOr Class, Refer PosFormat
Sparse_hash_map:
STL similar entities; refer to STL naming conventions
Longlong_max:
Constant, like Int_max

Google open-source project Style Guide

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.