Skip to content
Snippets Groups Projects
Commit ae3d7244 authored by Gururaj Shetty's avatar Gururaj Shetty
Browse files

Update C++ Coding Style Guide.rst

parent a9e96173
No related branches found
No related tags found
No related merge requests found
......@@ -272,7 +272,7 @@ member variables use the lowerCamelCase naming style.
const unsigned int DEFAULT_FILE_SIZE_KB = 200; // Global variable
}
Formatting
Formatting
**********
Line Length
......@@ -942,7 +942,7 @@ Classes
=======
Rule 3.15.1 Class access specifier declarations are in the sequence: public, protected, private. Indent these specifiers to the same level as the class keyword.
----------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
.. code:: cpp
......@@ -997,4 +997,462 @@ Rule 3.15.2 The constructor initialization list must be on the same line or wrap
someOtherVar_(var + 1)
{
DoSomething();
}
\ No newline at end of file
}
Comments
********
Generally, clear architecture and good naming are recommended to improve code readability, and comments are provided only when necessary.
Comments are used to help readers quickly understand code. Therefore, **comments should be provided for the sake of readers**.
Comments must be concise, clear, and unambiguous, ensuring that information is complete and not redundant.
**Comments are as important as code**.
When writing a comment, you need to step into the reader’s shoes and use comments to express what the reader really needs. Comments are used to express the function and intention of code, rather than
repeating code.
When modifying the code, ensure that the comments are consistent with the modified code. It is not polite to modify only code and keep the old comments, which will undermine the consistency between code and
comments, and may confuse or even mislead readers.
Comments should be made in English.
Comment Style
=============
In C++ code, both ``/* */`` and ``//`` can be used for commenting.
Comments can be classified into different types, such as file header comments, function header comments, and code comments. This is based on their purposes and positions.
Comments of the same type must keep a consistent style.
Note: Example code in this document uses comments in the ``//`` format
only to better describe the rules and recommendations. This does not
mean this comment format is better.
File Header Comments
====================
Rule 4.2.1 File header comments must contain the copyright notice.
------------------------------------------------------------------
/ Copyright (c) 2020 Huawei Device Co., Ltd. \* Licensed under the
Apache License, Version 2.0 (the “License”); \* you may not use this
file except in compliance with the License. \* You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
required by applicable law or agreed to in writing, software \*
distributed under the License is distributed on an “AS IS” BASIS, \*
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\* See the License for the specific language governing permissions and
\* limitations under the License. \*/
Function Header Comments
========================
Rule 4.3.1 Function header comments with no content are forbidden.
------------------------------------------------------------------
Not all functions need function header comments. For information that
cannot be described by function signatures, add function header
comments.
Function header comments are placed above the function declaration or
definition. Use one of the following styles: Use ‘//’ to start the
function header.
.. code:: cpp
// Single-line function header
int Func1(void);
// Multi-line function header
// Second line
int Func2(void);
Use ``/* */`` to start the function header.
.. code:: cpp
/* Single-line function header */
int Func1(void);
/*
* Another single-line function header
*/
int Func2(void);
/*
* Multi-line function header
* Second line
*/
int Func3(void);
Use function names to describe functions, and add function header
comments if necessary. Do not write useless or redundant function
headers. Do not write empty function headers with no content.
The function header comment content will depend on the function and
includes but is not limited to: a function description, return value,
performance constraints, usage comments, memory conventions, algorithm
implementation, reentering requirements. In the function interface
declaration in the external header file, the function header comment
should clearly describe important and useful information.
Good example:
.. code:: cpp
/*
* The number of written bytes is returned. If -1 is returned, the write operation failed.
* Note that the memory buffer should be released by the caller.
*/
int WriteString(const char *buf, int len);
Bad example:
.. code:: cpp
/*
* Function name: WriteString
* Function: Write a character string.
* Parameters:
* Return value:
*/
int WriteString(const char *buf, int len);
Problems:
- The ‘Parameters’ and ‘Return value’ have no content.
- The function name is redundant.
- The most import thing, that is, who needs to release the buffer, is
not clearly stated.
Code Comments
=============
Rule 4.4.1 Code comments are placed above or on the right of the corresponding code.
------------------------------------------------------------------------------------
Rule 4.4.2 There must be a space between the comment character and the comment content. At least one space is required between the comment and code if the comment is placed to the right of code.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Comments placed above code should be indented the same as that of the
code. Use one of the following styles: Use “//”.
.. code:: cpp
// Single-line comment
DoSomething();
// Multi-line comment
// Second line
DoSomething();
Use ``/* */``.
.. code:: cpp
/* Single-line comment */
DoSomething();
/*
* Multi-line comment in another mode
* Second line
*/
DoSomething();
Leave at least one space between the code and the comment on the right.
It is recommended that no more than four spaces be left. You can use the
Tab key to indent 1–4 spaces.
Select and use one of the following styles:
.. code:: cpp
int foo = 100; // Comment on the right
int bar = 200; /* Comment on the right */
It is more appealing sometimes when the comment is placed on the right
of code and the comments and code are aligned vertically. After the
alignment, ensure that the comment is 1–4 spaces away from the widest
line of code. For example:
.. code:: cpp
const int A_CONST = 100; /* Related comments of the same type can be aligned vertically. */
const int ANOTHER_CONST = 200; /* Leave spaces after code to align comments vertically. */
When the comment on the right exceeds the line width, consider placing
the comment above the code.
Rule 4.4.3 Delete unused code segments. Do not comment them out.
----------------------------------------------------------------
Code that is commented out cannot be maintained. If you attempt to
restore the code, it is very likely to introduce ignorable defects. The
correct method is to delete unnecessary code directly. If necessary,
consider porting or rewriting the code.
Here, commenting out refers to the removal of code from compilation
without actually deleting it. This is done by using /\* \*/, //, #if 0,
#ifdef NEVER_DEFINED, and so on.
Recommendation 4.4.1 Delivered code cannot contain a TODO/TBD/FIXME comment.
----------------------------------------------------------------------------
TODO/TBD comments are used to describe required improvements and
supplements. FIXME comments are used to describe defects that need
fixing. They should have a standardized style, which facilitates text
search. For example:
.. code:: cpp
// TODO(<author-name>): XX
// FIXME: XX
Header Files
************
Header File Responsibility
==========================
A header file is an external interface of a module or file. The design
of a header file shows most of the system design. The interface
declaration for most functions is more suitable placed in the header
file, but implementation (except inline functions) cannot be placed in
the header file. Functions, macros, enumerations, and structure
definitions that need to be used in .cpp files cannot be placed in the
header file. The header responsibility should be simple. An overly
complex header file will make dependencies complex and cause long
compilation times.
Recommendation 5.1.1 Each .cpp file should have a .h file with the same name. It should be used to declare the classes and interfaces that need to be exposed externally.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Generally, each .cpp file has a corresponding .h file. This .cpp file is
used to store the function declarations, macro definitions, and class
definitions that are to be exposed. If a .cpp file does not need to open
any interface externally, it should not exist. Exception: **An entry
point (for example, the file where the main function is located), unit
tests, and dynamic libraries**
For example:
.. code:: cpp
// Foo.h
#ifndef FOO_H
#define FOO_H
class Foo {
public:
Foo();
void Fun();
private:
int value_;
};
#endif
.. code:: cpp
// Foo.cpp
#include "Foo.h"
namespace { // Good: The declaration of the internal function is placed in the header of the .cpp file, and has been limited to the unnamed namespace or static scope.
void Bar()
{
}
}
...
void Foo::Fun()
{
Bar();
}
Header File Dependency
======================
Rule 5.2.1 Header file cyclic dependency is forbidden.
------------------------------------------------------
An example of cyclic dependency (also known as circular dependency) is: a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any of these header files is modified, all code containing a.h, b.h, and
c.h needs to be recompiled.
For a unidirectional dependency, for example if: a.h contains b.h, b.h contains c.h, and c.h does not contain any header file, modifying a.h does not mean that we need to recompile the source code for b.h or
c.h.
The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization.
Rule 5.2.2 Header files should have #define guards to prevent multiple inclusion.
---------------------------------------------------------------------------------
To prevent header files from being included multiple times, all header files should be protected by #define. Do not use #pragma once.
When defining a protection character, comply with the following rules:
The protection character uses a unique name. 2) Do not place code or comments (except for file header comments) before or after the protected
part.
Example: Assume that the timer.h file of the timer module is in the timer/include/timer.h directory. Perform the following operations to safeguard the timer.h file:
.. code:: cpp
#ifndef TIMER_INCLUDE_TIMER_H
#define TIMER_INCLUDE_TIMER_H
...
#endif
Rule 5.2.3 It is prohibited to reference external function interfaces and variables in extern declaration mode.
---------------------------------------------------------------------------------------------------------------
Interfaces provided by other modules or files can be used only by
including header files. Using external function interfaces and variables
in extern declaration mode may cause inconsistency between declarations
and definitions when external interfaces are changed. In addition, this
kind of implicit dependency may cause architecture corruption.
Cases that do not comply with specifications:
// a.cpp content
.. code:: cpp
extern int Fun(); // Bad: Use external functions in extern mode.
void Bar()
{
int i = Fun();
...
}
// b.cpp content
.. code:: cpp
int Fun()
{
// Do something
}
Should be changed to:
// a.cpp content
.. code:: cpp
#include "b.h" // Good: Use the interface provided by other .cpp by including its corresponding header file.
void Bar()
{
int i = Fun();
...
}
// b.h content
.. code:: cpp
int Fun();
// b.cpp content
.. code:: cpp
int Fun()
{
// Do something
}
In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used. For
example: When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. When a
function needs to be stubbed or patched, the function can be declared using extern.
Rule 5.2.4 Do not include header files in extern “C”.
-----------------------------------------------------
If a header file is included in extern “C”, extern “C” may be nested.
Some compilers restrict the nesting of extern “C”. If there are too many
nested layers, compilation errors may occur.
When C and C++ programmings are used together and if extern “C” includes
a header file, the original intent behind the header file may be
hindered. For example, when the link specifications are modified
incorrectly.
For example, assume that there are two header files a.h and b.h.
// a.h content
.. code:: cpp
...
#ifdef __cplusplus
void Foo(int);
#define A(value) Foo(value)
#else
void A(int)
#endif
// b.h content
.. code:: cpp
...
#ifdef __cplusplus
extern "C" {
#endif
#include "a.h"
void B();
#ifdef __cplusplus
}
#endif
Using the C++ preprocessor to expand b.h, the following information is
displayed:
.. code:: cpp
extern "C" {
void Foo(int);
void B();
}
According to the author of a.h, the function Foo is a C++ free function
following the “C++” link specification. However, because
``#include "a.h"`` is placed inside ``extern "C"`` in b.h, the link
specification of function Foo is changed incorrectly.
Exception: In the C++ compilation environment, if you want to reference
the header file of pure C, the C header files should not contain
``extern "C"``. The non-intrusive approach is to include the C header
file in ``extern "C"``.
Recommendation 5.2.1 Use ``#include`` instead of a forward declaration to include header files.
-----------------------------------------------------------------------------------------------
A forward declaration is for the declaration of classes, functions, and
templates and is not meant for its definition.
* Advantages:
* Forward declarations can save compilation time. Redundant ``#include``\ statements force the compiler to expand more files and process more input.
* Forward declarations can save unnecessary recompilation time. The use of #include will force your code to be recompiled multiple times due to
unrelated changes in header files.
* Disadvantages:
* Forward declarations hide dependency relationship. When a header file is modified, user code will skip the necessary recompilation process.
* A forward declaration may be broken by subsequent changes to the library. Forward declarations of functions and templates sometimes prevent
header file developers from changing APIs. For example, widening a formal parameter type, adding a template parameter with a default value, and so
on.
* Forward declaration of symbols from the namespace ``std::`` is seen as undefined behavior (as specified in the C++ 11 standard specification).
* Forward declaration of multiple symbols from a header file can be more verbose than simply including (#include) the header.
* Structuring code only for forward declaration (for example, using pointer members instead of object members) can make the code more
complex and slower.
* It is difficult to determine whether a forward declaration or ``#include`` is needed. In some scenarios, replacing ``#include``
with a forward declaration may cause unexpected results.
Therefore, we should avoid using forward declarations as much as possible. Instead, we use the #include statement to include a header
file and ensure dependency.
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment