Embedded c language coding specification

Students who study embedded should first master the embedded coding specification, so as to better the embedded system.

Let's explain the embedded c coding specification from these aspects.

Comment style, typesetting style, header file style, variable definition, macro definition, function

1 Comment style

1.1 The principle of comments is to facilitate the reading and understanding of the program, and the comments should not be too many or too few. Comment language must be accurate, understandable, concise, and unambiguous.

1.2 The header code of the program file should be commented. Comments must list: copyright statement, version number, generation date, author, content, function, relationship to other files, modification log, etc. There should also be a brief description of the function function in the comments of the header file.

/*

* Copyright(C), 2007-2008, Red Hat Inc. // Copyright Notice

* File name: // file name

* Author: // author

* Version: // version

* Date: // Completion date

* Description: // Describe the function of this file and the relationship with other modules

* Function List: // A list of main functions, each record should include the function name and a brief description of the function

* History: // Modification history, including the date of each modification, the person who modified it, and a brief description of the modified content

*/

1.3 The function header should be annotated, listing the function, input parameters, output parameters, return value, calling relationship, etc. of the function.

/*

* Function: // function name

* Description: // Description of function function, performance, etc.

* Calls: // List of functions called by this function

* Called By: // List of functions calling this function

* Input: // Input parameter description, including the function of each parameter

* Output: // Output parameter description, sometimes returns some variable values ​​through pointer parameters

* Return: // Description of function return value

* Others: // Other instructions

*/

1.4 For all variables, constants, macros, structures and other data structures with specific meanings, if their names are not fully self-explanatory, they must be declared with comments to explain their actual meanings. Comments for variables, constants, and macros should be placed above or to the right of them.

1.5 Global variables should have more detailed comments, including functions, value ranges, which functions access it, and precautions when accessing.

1.6 In order to make the typesetting of the program neat and easy to read and understand, comments should also be indented and aligned.

void example_function( void )

{

     /* comments one */

     unsigned int min_port, max_port;

     /* comments two */

     if ...

}

1.7 Add a comment to the right of the end line of a complex program block to indicate the end of a program block.

Example:

if (...)

{

    ...

    while ( ... )

    {

      ...

    } /* while ( ... ) loop statement ends */

     ...

} /* end of if (...) statement end */ 

2 typography style

2.1 Blank lines must be added between relatively independent program blocks and after variable declarations.

int          conn_fd;

int          ret;

conn_fd = socket(AF_INET, SOCK_STREAM,0);

if (conn_fd < 0) {

    perror("socket create");

}

2.2 Program blocks should be written in an indented style, and the indentation should be 4 spaces or a Tab key.

2.3 For longer sentences (more than 80 characters), they should be written in multiple lines, and the new lines should be indented appropriately to make the typesetting neat and the sentences readable. Functions with long parameters should also be divided into multiple lines.

ret = connect(conn_fd, (struct sockaddr *)&serv_addr, 

                  sizeof (struct sockaddr));

2.4 Write only one statement in one line, and it is not allowed to write multiple short statements in one line.

The following statements are not canonical:

min_port = 1; max_port = 65535;

It should be written as follows:

min_port = 1; 

max_port = 65535;

2.5 Statements such as if, for, do, while, case, switch, and default occupy one line each, and brackets { } should be added to the execution statement part of if, for, do, while and other statements no matter how many.

The following statements are not canonical:

if (conn_fd < 0) perror("socket create");

It should be written as follows:

if (conn_fd < 0) {

     perror("socket create");

}

2.6 '{' and '}' must be on a single line

for (i=1; i<argc; i++)

{

     ...

}

Or in the code, '{' goes with the for statement, and there must be a space before '{'.

for (i=1; i<argc; i++) {

     ...

}

2.7 Use of spaces

(1) Add a space after the comma in the following statement.

     int min_port, max_port;

(2) "+", "-", "*", "=" and other arithmetic operators have a space on both sides.

     a = i + j;

(3) "<", ">=" and other comparison operators have a space on both sides.

     if (conn_fd < 0) {

(4) "!", "~", "++", "--", "&" (address operator) and other unary operators do not add spaces before and after.

     i++;

(5) There are no spaces before and after "->" and ".".

     portinfo.min_port = i * seg_len + 1;

3 Variable definition

3.1 Variable names should be clear and clear, with clear meanings. At the same time, use complete words or abbreviations that everyone can understand to avoid misunderstandings.

Example:

Temp can be abbreviated as tmp

message can be abbreviated as msg

3.2 For variable naming, it is forbidden to use a single character (such as i, j, k). It is recommended that in addition to having a specific meaning, it can also indicate its data type, etc., but i, j, k are allowed as local loop variables.

int iwidth; // i indicates that the variable is int type, width indicates the width

3.3 Under Linux, variable names are generally all lowercase and underlined.

General use:

int min_port;

Generally not used:

int minPort;

3.4 When using global variables in multi-threaded programs, attention should be paid to the atomicity of variable operations.

3.5 It should be avoided that local variables have the same name as global variables.

3.6 It is strictly forbidden to use uninitialized variables as rvalues. In a C program, referencing an unassigned pointer often causes the program to crash.

The following code will cause an error under Linux, because it is wrong to operate p_string without pointing to a certain memory space.

char *p_string;

p_sting[0] = ‘a’;

It should be initialized first:

char *p_string;

p_string = (char *)malloc(BUFF_SIZE); // here assumes that BUFF_SIZE is defined

p_sting[0] = ‘a’;     

4 Macro definition

4.1 Use less literal constants in the code, and use macro constants instead.

4.2 Macro names should be capitalized as much as possible when defining macros

4.3 If the macro name consists of multiple words, add _ between each word

#define BUFF_SIZE          1024

input_data = (char *)malloc(BUFF_SIZE);

4.4 When using macros to define expressions, complete parentheses should be used.

There are certain risks associated with macros defined as follows:

#define GET_AREA(a,b)     a*b

should be defined as:

#define GET_AREA(a,b)     ((a)*(b))

4.5 If there are multiple statements in a macro, these statements should be enclosed in a pair of braces.

In the following statement only the first expression of the macro is executed.

#define INTI_RECT_VALUE( a, b )\

    a = 0;\

    b = 0;

for (index = 0; index < RECT_TOTAL_NUM; index++)

             INTI_RECT_VALUE( rect.a, rect.b );

The correct usage should be:

#define INTI_RECT_VALUE( a, b ) {\

            a = 0;\

            b = 0;\

}

for (index = 0; index < RECT_TOTAL_NUM; index++) { 

          INTI_RECT_VALUE( rect[index].a, rect[index].b );

}

5 function definition

5.1 A function completes a specific function, and should not try to realize multiple unrelated functions in one function.

5.2 Check the validity of all input parameters of the function, such as whether the pointer parameter is empty, and whether the array member parameter is out of bounds.

5.3 The size of a function should be limited to 200 lines (excluding blank lines and comment lines).

5.4 The function of the function should be predictable, that is, as long as the input data is the same, it should produce the same expected output.

5.5 The parameters of the function should not be too many, preferably 1-3.

5.6 The function name should accurately describe the function of the function, and it is generally named in the form of a verb and an object.

void print_record( struct *p_record, int record_len) ;

5.7 The return value of the function should be clear and clear, so that the user is not easy to ignore the error condition. The meaning of each error return value of the function should be clear and clear, so as to prevent users from misusing, misunderstood or ignoring the error return code.

5.8 If multiple pieces of code do the same thing repeatedly, then you should consider implementing the repetitive functionality as a function.

5.9 Reduce the recursive calls of the function itself or between functions.

Recursive calls, especially recursive calls between functions (such as A->B->C->A), affect the intelligibility of the program; recursive calls generally occupy more system resources (such as stack space); The test is not good.

6 header file styles

6.1 The header file can save the following contents: macro definition, type definition, structure definition, variable declaration, function declaration

    Do not have the following: variable definition, function definition

6.2 Header files must have duplicate inclusion restrictions

#ifndef _ALPS_H

#define _ALPS_H

...

#endif

Embedded Internet of Things needs to learn a lot. Don't learn the wrong route and content, which will cause your salary to go up!

Share a data package with everyone, about 150 G. The learning content, face-to-face scriptures, and projects in it are relatively new and complete! (Click to find a small assistant to receive)

Guess you like

Origin blog.csdn.net/m0_70911440/article/details/131654443