NuttX C Coding StandardLast Updated: August 24, 2016 |
Table of Contents |
if then else
Statementswitch
Statementwhile
Statementdo while
Statementgoto
1.0 General Organization |
File Extensions
Use the .h
extension for C header files and .c
for C source files.
File header. Every C, C++, make file, or script begins with a file header. That file header is enclosed with a block comment (see below). Within the block comment, the following must appear:
Sample File Headers.
Sample file headers are provided in an Appendix to this document.
No software may be included in the NuttX source tree that does not have licensing information included in the file.
No software may be included in the NuttX source tree that does not have a (modified) BSD license or compatible license (such as the MIT license).
If the file does not following BSD licensing, then the appropriate license information should be provided in the header rather than the (modified) BSD licensing information and a NOTE should be included in the top-level COPYING
file to indicate any variations from (modified) BSD licensing.
Grouping. All like components in a C source or header file are grouped together. Definitions do not appear arbitrarily through the file, rather, like definitions are grouped together and preceded by a block comment identifying the grouping.
Block Comments. Each grouping in the file is separated with a block comment. The block comment consists of:
/*
) followed by a series of asterisks extending to the length of the line (usually to column 78).
*/
) at the end of the line (usually column 78) preceded by a series of asterisks extending to column 1.
Examples of Block Comments. See Appendix A for examples of block comments.
Order of Groupings. The following groupings should appear in all C source files in the following order:
The following groupings should appear in all C header files in the following order:
Large vs. Small Files. In larger files, block comments should be included for all groupings, even if they are empty; the empty grouping provides important information in itself. Smaller files may omit some of the block comments; it is awkard if the block comments are larger than the file content!
Header File Idempotence. C header file must protect against multiple inclusion through the use of macros that "guard" against multiple definitions if the header file is included multiple times.
Each header file must contain the following pre-processor conditional logic near the beginning of the header file: Between the file header and the "Included Files" block comment. For example,
#ifndef __INCLUDE_NUTTX_ARCH_H #define __INCLUDE_NUTTX_ARCH_H
Notice that the definitions within of the header do not follow the usually rules: The presence of the conditional test at the top of the file does not cause the remaining definitions within the file to be indented.
Then conditional compilation is closed at the fine line of the header file with:
#endif /* __INCLUDE_NUTTX_ARCH_H */
Forming Guard Names.
Then pre-processor macro name used in the guard is formed from the full, relative path to the header for from the top-level, controlled directory.
That pat is preceded by __
and _
replaces each character that would otherwise be invalid in a macro name.
So, for example, __INCLUDE_NUTTX_ARCH_H corresponds to the header file include/nuttx/arch.h
Deoxygen Information. NuttX does not use Deoxygen for documentation and no file should contain Doxygen tags or Doxygen style comments.
Sample File Formats. C source and header file templates are provided in an Appendix to this document.
Line Endings.
Files should be formatted with \n
as the line ending (Unix line endings), not \r\n
(Windows line endings).
There should be no extra whitespace at the end of the line.
In addition, all text files should end in a single newline (\n
). This avoids the "No newline at end of file" warning generated by certain tools.
Line Width. Text should not extend past column 78 in the typical C source or header file. Sometimes the nature of the content of a file may require that the lines exceed this limit. This often occurs in header files with naturally long definitions. If the line width must extend 78 lines, then some wider line width may be used in the file provided that it is used consistently.
Line Wrapping.
Incorrect struct some_long_struct_name_s { struct some_long_struct_name_s *flink; /* The forward link to the next instance of struct some_long_struct_name_s in a singly linked list */ int short_name1; /* Short comment 1 */ int short_name2; /* This is a very long comment describing subtle aspects of the short_name2 field */ }; struct some_medium_name_s *ptr = (struct some_medium_name_s *)malloc(sizeof(some_medium_name_s); struct some_long_struct_name_s *ptr = (struct some_long_struct_name_s *)malloc(sizeof(some_long_struct_name_s); ret = some_function_with_many parameters(long_parameter_name_1, long_parameter_name_2, long_parameter_name_3, long_parameter_name_4, long_parameter_name_5, long_parameter_name_6, long_parameter_name_7, long_parameter_name_8); ret = some_function_with_many parameters(long_parameter_name_1, long_parameter_name_2, long_parameter_name_3 long_parameter_name_4, long_parameter_name_5, long_parameter_name_6, long_parameter_name_7, long_parameter_name_8); |
Correct struct some_long_struct_name_s { /* The forward link to the next instance of struct * some_long_struct_name_s in a singly linked list. */ struct some_long_struct_name_s *flink; int short_name1; /* Short comment 1. */ int short_name2; /* This is a very long comment describing subtle * aspects of the short_name2 field. */ }; FAR struct some_medium_name_s *ptr = (FAR struct some_medium_name_s *) malloc(sizeof(some_medium_name_s); FAR struct some_medium_name_s *ptr = (FAR struct some_medium_name_s *)malloc(sizeof(some_medium_name_s); FAR struct some_long_struct_name_s *ptr = (FAR struct some_long_struct_name_s *) malloc(sizeof(some_long_struct_name_s); ret = some_function_with_many parameters(long_parameter_name_1, long_parameter_name_2, long_parameter_name_3, long_parameter_name_4, long_parameter_name_5, long_parameter_name_6, long_parameter_name_7, long_parameter_name_8); |
NOTE:
See the discussion of pointers for information about the FAR
qualifier used above.
Double Spacing. A single blank line may be use to separate logical groupings as the designer feels fit. Single blank lines are also required in certain contexts as defined in this standard. Additional blanks lines (two or more) are prohibited.
Columnar Organization. Similar things should be aligned on the same column unless doing so would cause the line width to be exceeded.
Acceptable dog = cat; monkey = oxen; aardvark = macaque; |
Preferred dog = cat; monkey = oxen; aardvark = macaque; |
Block Comments
The final asterisk (*
) should occur at column 78 (or the line width of files with longer lines).
Note that the final comment delimiter of the block comment is an exception an lies at column 79.
General. Within a comment, the text must be standard English conforming to standard English rules of grammar and spelling (US English spelling). Of course, this is not the place to summarize all English grammar, but as examples of common grammatic issues in comments:
Line Spacing A single blank line should precede and follow each comment. The only exception is for the file header block comment that begins on line one; there is no preceding blank line in that case.
Incorrect /* set a equal to b */ a = b; /* set b equal to c */ b = c; |
Correct /* Set a equal to b. */ a = b; /* Set b equal to c. */ b = c; |
Indentation Comments should, typically, be placed before the code section to which they apply. The comment identation should be the same as the follow identation rules as the following code (if applicable).
Short, Single line comments. Short comments must lie on a single line. The comment delimiters must lie on the same line.
Incorrect /* * This is a single line comment */ |
Correct /* This is a single line comment. */ |
Multi-line comments.
If the comment is too long to fit on a single, it must be broken into a multi-line comment.
The comment must be begin on the first line of the multi-line comment with the opening comment delimiter (/*
).
The following lines of the multi-line comment must be with an asterisk (*
) aligned in the same column as the asterisk in the preceding line.
The closing comment delimiter must lie on a separate line with the asterisk (*
) aligned in the same column as the asterisk in the preceding line.
Incorrect /* This is the first line of a multi-line comment. This is the second line of a multi-line comment. This is the third line of a multi-line comment. */ /* This is the first line of another multi-line comment. */ /* This is the second line of another multi-line comment. */ /* This is the third line of another multi-line comment. */ |
Correct /* This is the first line of a multi-line comment. * This is the second line of a multi-line comment. * This is the third line of a multi-line comment. */ |
Comments to the Right of Statements. Comments to the right of statements in C source files are discouraged. If such comments are used, they should be (1) very short so that they do not exceed the line width (typically 78 characters), (2) fit on one line, and (3) be aligned so that the comment begins in the same comment on each line.
Incorrect dog = cat; /* Make the dog be a cat */ monkey = oxen; /* Make the monkey be an oxen */ aardvark = macaque; /* Make the aardvark be a macaque */ |
Acceptable dog = cat; /* Make the dog be a cat. */ monkey = oxen; /* Make the monkey be an oxen. */ aardvark = macaque; /* Make the aardvark be a macaque. */ |
Preferred /* Make the dog be a cat. */ dog = cat; /* Make the monkey be an oxen. */ monkey = oxen; /* Make the aardvark be a macaque. */ aardvark = macaque; |
Comments to the Right of Data Definitions. Comments to the right of a declaration with an enumeration or structure, on the other hand, are encouraged, provided that the comments are short and do not exceed the maximum line width (usually 78 characters). Columnar alignment of comments is very desireable (but often cannot be achieved without violating the line width).
Incorrect struct animals_s { int dog; /* This is a dog */ int cat; /* This is a cat */ double monkey; /* This is a monkey */ double oxen; /* This is an oxen */ bool aardvark; /* This is an aardvark */ bool macaque; /* This is a macaque */ }; |
Acceptable struct animals_s { int dog; /* This is a dog. */ int cat; /* This is a cat. */ double monkey; /* This is a monkey. */ double oxen; /* This is an oxen. */ bool aardvark; /* This is an aardvark. */ bool macaque; /* This is a macaque. */ }; |
Preferred struct animals_s { int dog; /* This is a dog. */ int cat; /* This is a cat. */ double monkey; /* This is a monkey. */ double oxen; /* This is an oxen. */ bool aardvark; /* This is an aardvark. */ bool macaque; /* This is a macaque. */ }; |
Long Comments on the Right. Comments on the right of statements or data definitions must be short and fit on the same line without exceeding the maximum line length. If a longer comment is needed, then it should appear above the statement of definition rather than to the right of the definition.
Incorrect dog = cat; /* This assignment will convert what was at one time a lowly dog into a ferocious feline. */ |
Acceptable dog = cat; /* This assignment will convert what was at one time a * lowly dog into a ferocious feline. */ |
Preferred /* This assignment will convert what was at one time a lowly dog into a * ferocious feline. */ dog = cat; |
Note that if the comment is continued on multiple lines, the comment alignment and multi-line comment rules still apply with one exception: The closing */
appears on the same line as the final text of the comment. This exception to the rule is enforced to keep the statements and definitions from becoming to spread out.
Block comments. Block comments are only used to delimit groupings with the overall file organization and should not be used unless the usage is consistent with delimiting logical groupings in the program.
C Style Comments.
C99/C11/C++ style comments (beginning wih //
) should not be used with NuttX.
NuttX generally follows C89 and all code outside of architecture specific directories must be compatible with C89.
Incorrect // This is a structure of animals struct animals_s { int dog; // This is a dog int cat; // This is a cat double monkey; // This is a monkey double oxen; // This is an oxen bool aardvark; // This is an aardvark bool macaque; // This is a macaque }; |
Correct /* This is a structure of animals. */ struct animals_s { int dog; /* This is a dog. */ int cat; /* This is a cat. */ double monkey; /* This is a monkey. */ double oxen; /* This is an oxen. */ bool aardvark; /* This is an aardvark. */ bool macaque; /* This is a macaque. */ }; |
"Commenting Out" Large Code Blocks.
Do not use C or C++ comments to disable compilation of large blocks of code.
Instead, use #if 0
to do that.
Make sure there is a comment before the #if 0
to explain why the code is not compiled.
Incorrect void some_function(void) { ... compiled code ... /* ... disabled code .. */ ... compiled code ... } void some_function(void) { ... compiled code ... // // ... disabled code .. // ... compiled code ... } |
Correct void some_function(void) { ... compiled code ... /* The following code is disabled because it is no longer needed. */ #if 0 ... disabled code .. #endif ... compiled code ... } |
Coding Standard:
Incorrect while (true) { if (valid) { ... } /* if valid */ else { ... } /* not valid */ } /* end forever */ |
Correct while (true) { if (valid) { ... } else { ... } } |
Exceptions. The exception is braces that following structure, enumeration, union, and function declarations. There is no additional indentation for those braces; those braces align with the beginning of the definition
Incorrect enum kinds_of_dogs_e { ... }; struct dogs_s { ... union { ... } u; ... }; struct cats_s { ... union { ... } u; ... }; int animals(int animal) { ... } |
Correct enum kinds_of_dogs_e { ... }; struct dogs_s { ... union { ... } u; ... }; struct cats_s { ... union { ... } u; ... }; int animals(int animal) { ... } |
Indentation Unit. Indentation is in units of two spaces; Each indentation level is twos spaces further to the right than the preceding identation levels.
Incorrect if (x == y) { dosomething(x); } if (x == y) { dosomething(x); } |
Correct if (x == y) { dosomething(x); } |
Use of TAB Characters. The use of TAB characters for indentation is prohibited in C source and header files. TAB characters are, however, used in make files, assembly language source files, Kconfig files and some script files. When TAB characters are used in these files, spaces may not be used for indentation. The correct TAB setting is 4 spaces (not 8) in these cases.
Alignment of Braces. Note that since braces must be on a separate line (see above), this indentation by two spaces has an interesting property: All C statements (and case selectors) like on lines that are odd multiples of 2 spaces: 2, 6, 10, ... (2*n + 1). A braces lie on a separate line indented by an even multple of 2 spaces: 4, 8, 12, ... 2*n.
Indentation of Pre-Processor Lines.
C Pre-processor commands following any conditional computation are also indented following basically the indentation same rules, differing in that the #
always remains in column 1.
Incorrect #ifdef CONFIG_ABC #define ABC_THING1 1 #define ABC_THING2 2 #define ABC_THING3 3 #endif #ifdef CONFIG_ABC #define ABC_THING1 1 #define ABC_THING2 2 #define ABC_THING3 3 #endif |
Correct #ifdef CONFIG_ABC # define ABC_THING1 1 # define ABC_THING2 2 # define ABC_THING3 3 #endif #ifdef CONFIG_ABC # define ABC_THING1 1 # define ABC_THING2 2 # define ABC_THING3 3 #endif |
Exception. Each header file includes idempotence definitions at the beginning of the header file. This conditional compilation does not cause any change to the indentation.
Incorrect #ifndef __INCLUDE_SOMEHEADER_H # define __INCLUDE_SOMEHEADER_H ... # define THING1 1 # define THING2 2 # define THING3 3 ... #endif /* __INCLUDE_SOMEHEADER_H */ |
Correct #ifndef __INCLUDE_SOMEHEADER_H #define __INCLUDE_SOMEHEADER_H ... #define THING1 1 #define THING2 2 #define THING3 3 ... #endif /* __INCLUDE_SOMEHEADER_H */ |
Coding Standard:
(
) immediately after any C keywords (for
, switch
, while
, do
, return
, etc.).
Put a space before the left parenthesis in these cases.
)
).
Incorrect int do_foobar ( void ) { int ret = 0; int i; for( i = 0; ( ( i < 5 ) || ( ret < 10 ) ); i++ ) { ret = foobar ( i ); } return ( ret ); } |
Correct int do_foobar(void) { int ret = 0; int i; for (i = 0; i < 5 || ret < 10; i++) { ret = foobar(i); } return ret; } |
NOTE: Many people do not trust their understanding of the precedence of operators and so use lots of parentheses in expressions to force the order of evaluation even though the parentheses may have no effect. This will certainly avoid errors due to an unexpected order of evaluation, but can also make the code ugly and overly complex (as in the above example). In general, NuttX does not use unnecessary parentheses to force order of operations. There is no particular policy in this regard. However, you are are advised to check your C Programming Language book if necessary and avoid unnecessary parenthesis when possible.
2.0 Data and Type Definitions |
Incorrect extern long time, money; char **ach, *bch; int i, j, k; |
Correct extern long time; extern long money; FAR char **ach; FAR char *bch; int i; int j; int k; |
NOTE:
See the discussion of pointers for information about the FAR
qualifier used above.
Coding Standard:
g_filelen
is preferable to something like g_lengthoffile
.
g_
to indicate the scope of variable.
xyz
, then that module should be included as part of the prefix like: g_xyz_
.
'_'
.
Preferably there are no '_'
separators within the name.
Long variable names might require some delimitation using '_'
.
Long variable names, however, are discouraged.
Incorrect extern int someint; uint32_t dwA32BitInt; uint32_t gAGlobalVariable; |
Acceptable extern int g_someint; uint32_t g_a32bitint; uint32_t g_aglobal; |
Preferred struct my_variables_s { uint32_t a32bitint; uint32_t aglobal; }; extern int g_someint; struct my_variables_s g_myvariables; |
Coding Standard:
len
is preferable to something like lengthofiobuffer
.
p
or pp
may be used on names of pointers (or pointer to pointers) if it helps to distinguish the variable from some other local variable with a similar name.
Even this convention is discouraged when not necessary.
i
, j
, and k
which are reserved only for use as loop indices
(part of our Fortran legacy).
'_'
.
Preferably there are no '_'
separators within the name.
Long variable names might require some delimitation using '_'
.
Long variable names, however, are discouraged.
Incorrect uint32_t somefunction(int a, uint32_t dwBValue) { uint32_t this_is_a_long_variable_name = 1; int i; for (i = 0; i < a; i++) { this_is_a_long_variable_name *= dwBValue--; } return this_is_a_long_variable_name; } |
Correct uint32_t somefunction(int limit, uint32_t value) { uint32_t ret = 1; int i; for (i = 0; i < limit; i++) { ret *= value--; } return ret; } |
NOTE:
You will see the local variable named ret
is frequently used in the code base for the name of a local variable whose value will be returned or to received the returned value from a called function.
Coding Standard:
fhandle_t
is preferable to something like openfilehandle_t
.
typedef
'ed names end with the suffix _t
.
xyz
, then that module should be included as a prefix to the type name like: xyz_
.
'_'
.
Preferably there are few '_'
separators within the type name.
Long type names might require some delimitation using '_'
.
Long type names, however, are discouraged.
Incorrect typedef void *myhandle; typedef int myInteger; |
Correct typedef FAR void *myhandle_t; typedef int myinteger_t; |
NOTE:
See the discussion of pointers for information about the FAR
qualifier used above.
Structure Naming
typdef
-ing of structures;
normally the full structure name is used as types throughout the code.
xyz_info_s
is preferable to something like xyz_datainputstatusinformation_s
.
_s
.
xyz
, then that module should be included as a prefix to the structure name like: xyz_
.
'_'
.
Preferably there are few '_'
separators within the structure name.
Long variable names might require some delimitation using '_'
.
Long variable names, however, are discouraged.
Structure Field Naming
'_'
.
Preferably there are few '_'
separators within the field name.
Long variable names might require some delimitation using '_'
.
Long variable names, however, are discouraged.
Other Applicable Coding Standards. See sections related to line formatting, use of braces, indentation, and comments.
Size Optimizations.
When declaring fields in structures, order the declarations in such a way as to minimize memory waste due of data alignment.
This essentially means that that fields should be organized by data size, not by functionality:
Put all pointers togeter, all uint8_t
's together, all uint32_t
's together.
Data types withi well known like uint8_t
and uint32_t
should also be place in either ascending or descending size order.
Incorrect typedef struct { ... int val1, val2, val3; /* Values 1-3 */ ... } xzy_info_t; struct xyz_information { ... uint8_t bita : 1, /* Bit A */ bitb : 1, /* Bit B */ bitc : 1; /* Bit C */ ... }; |
Correct struct xyz_info_s { ... int val1; /* Value 1. */ int val2; /* Value 2. */ int val3; /* Value 3. */ ... }; typdef struct xyz_info_s xzy_info_t; (The use of typedef'ed structures is acceptable but discouraged) struct xyz_info_s { ... uint8_t bita : 1, /* Bit A. */ uint8_t bitb : 1, /* Bit B. */ uint8_t bitc : 1, /* Bit C. */ ... }; |
Union and Field Names.
Naming of unions and fields within unions follow the same naming rules as for structures and structure fields.
The only difference is that the suffix _u
is used to identify unions.
Other Applicable Coding Standards. See sections related to line formatting, use of braces, indentation, and comments.
Example union xyz_union_u { uint8_t b[4]; /* Byte values. */ uint16_t h[2]; /* Half word values. */ uint32_t w; /* Word Value. */ }; struct xyz_info_s { ... union { uint8_t b[4]; /* Byte values. */ uint16_t h[2]; /* Half word values. */ uint32_t w; /* Word Value. */ } u; ... }; |
NOTE:
Note that the union name u
is used often.
This is another exception to the prohibition against using single character variable and field names.
The short field name u
clearly identifies a union field and prevents the full name to the union value from being excessively long.
Enumeration Naming.
Naming of enumerations follow the same naming rules as for structure and union naming.
The only difference is that the suffix _e
is used to identify an enumeration.
Enumeration Value Naming. Enumeration values, however, following a naming convention more similar to macros.
'_'
encouraged.
Unlike other naming, use of the underscore character _
to break up enumeration names is encouraged.
Other Applicable Coding Standards. See sections related to line formatting, use of braces, indentation, and comments.
Example enum xyz_state_e { XYZ_STATE_UNINITIALIZED = 0, /* Uninitialized state. */ XYZ_STATE_WAITING, /* Waiting for input state. */ XYZ_STATE_BUSY, /* Busy processing input state. */ XYZ_STATE_ERROR, /* Halted due to an error. */ XYZ_STATE_TERMINATING, /* Terminating stated. */ XYZ_STATE_TERMINATED /* Terminating stated. */ }; |
Coding Standard:
Macro Naming. Macro naming following a naming convention similar to the naming of enumeration values.
p
for a period or decimal point (such as VOLTAGE_3p3V
).
I have also used lower-case v
for a version number (such as CONFIG_NET_IPv6
).
However, these are exceptions to the rule rather than illustrating a rule.
'_'
encouraged.
Unlike other naming, use of the underscore character _
to break up macro names is encouraged.
#define
.
A single space character should separate the #define
from the macro name.
Tabs are never used.
\
character just before the newline character.
There should be a single space before the \
character.
Aligned \
characters on multiple line continuations are discouraged because they are a maintenance problem.
do { ... } while (0)
to assume that the macros is, indeed, a statement.
Other Applicable Coding Standards. See sections related to line formatting, indentation, and comments.
Incorrect #define max(a,b) a > b ? a : b #define ADD(x,y) x + y #ifdef HAVE_SOMEFUNCTION int somefunction(struct somestruct_s* psomething); #else #define SOMEFUNCTION() (0) #endif # define IS_A_CAT(c) ((c) == A_CAT) #define LONG_MACRO(a,b) \ { \ int value; \ value = b-1; \ a = b*value; \ } #define DO_ASSIGN(a,b) a = b |
Correct #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define ADD(x,y) ((x) + (y)) #ifdef HAVE_SOMEFUNCTION int somefunction(struct somestruct_s* psomething); #else # define somefunction(p) (0) #endif # define IS_A_CAT(c) ((c) == A_CAT) #define LONG_MACRO(a,b) \ { \ int value; \ value = (b)-1; \ (a) = (b)*value; \ } #define DO_ASSIGN(a,b) do { (a) = (b); } while (0) |
Pointer Naming.
Pointers following same naming conventions as for other variable types.
A pointer (or pointer-to-a-pointer) variable may be prefaced with p
(or pp
) with no intervening underscore character _
in order to identify that variable is a pointer.
That convention is not encouraged, however, and is only appropriate if there is some reason to be concerned that there might otherwise be confusion with another variable that differs only in not being a pointer.
White Space. The asterisk used in the declaration of a pointer variable or to dereference a pointer variable should be placed immediately before the variable name with no intervening spaces. A space should precede the asterisk in a cast to a pointer type.
Incorrect int somefunction(struct somestruct_s* psomething); ptr = (struct somestruct_s*)value; |
Correct int somefunction(FAR struct somestruct_s *something); ptr = (FAR struct somestruct_s *)value; |
FAR
, NEAR
, DSEG
and CODE
pointers.
Some architectures require a qualifier on pointers to identify the address space into which the pointer refers.
The macros FAR
, NEAR
, DSEG
and CODE
are defined in include/nuttx/compiler.h
to provide meaning for this qualifiers when needed.
For portability, the general rule is that pointers to data that may lie in the stack, heap, .bss
, or .data
should be prefaced by the qualifier FAR
; pointers to functions probably lie in a code address space and should have the qualifier CODE
.
The typical effect of these macros on architectures where they have meaning to determine the size of the pointer (size in the sense of the width of the pointer value in bits).
Applicable Coding Standards. See the section related to parentheses.
C89 Compatibility. All common NuttX code must conform to ANSII C89 requirements. Newer C standards permit more flexible initialization with named initializers and array initializers. However, these are not backward compatible with C89 and cannot be used in common code. Newer C99 features may be included in architecture-specific sub-directories where there is no possibility of the use of such older toolchains. C11 is included in NuttX, but has not been verified and, hence, it not encourage anywhere.
3.0 Functions |
Coding Standard:
/*
) followed by a series of asterisks extending to the length of the line (usually to column 78).
*
) in column 2, and a space in column 3.
* Name:
followed by the name of the function on the same line.
* Description:
followed by a description of the function beginning on the second line.
Each line of the function description is indented by two additional spaces.
* Input Parameters:
followed by a description of the of each input parameter beginning on the second line.
Each input parameter begins on a separator line indented by two additional spaces.
The description needs to include (1) the name of the input parameters, and (2) a short description of the input parameter.
* Returned Value:
followed by a description of the of returned value(s) beginning on the second line.
The description of the returned value should identify all error values returned by the function.
* Assumptions/Limitations:
followed by a any additional information that is needed to use the function correctly.
This section is optional and may be omitted with there is no such special information required for use of the function.
*
".
Function header template. Refer to Appendix A for the template for a function header.
Coding Standard:
xyz_putvalue
is preferable to something like xyz_savethenewvalueinthebuffer
.
'_'
, character.
For example, for a module called xyz, all of the functions should begin with xyz_
.
xyz_iob_
.
'_'
discouraged.
Further use of the '_'
separators is discouraged in function naming.
Long function names might require some additional elimitation using '_'
.
Long function names, however, are also discouraged.
true
should be consistent with result of the test being true.
Coding Standards. See general rules for parameter naming. See also the sections related to the use of parentheses.
Use of const
Parameters.
Use of the const
storage class is encouraged.
This is appropriate to indicate that the function will not modify the object.
Coding Standard:
OS Internal Functions.
In general, OS internal functions return a type int
to indicate success or failure conditions.
Non-negative values indicate success.
The return value of zero is the typical success return value, but other successful return can be represented with other positive values.
Errors are always reported with negative values.
These negative values must be a well-defined errno
as defined in the file nuttx/include/errno.h
.
Application/OS Interface. All but a few OS interfaces conform to documented standards that have precedence over the coding standards of this document.
Checking Return Values.
Callers of internal OS functions should always check return values for an error.
At a minimum, a debug statement should indicate that an error has occurred.
The calling logic intentionally ignores the returned value, then the function return value should be explicitly cast to (void)
to indicate that the return value is intentionally ignored.
An exception of for standard functions for which people have historically ignored the returned values, such as printf()
or close
.
All calls to malloc
or realloc
must be checked for failures to allocate memory.
4.0 Statements |
Coding Standard:
Other Applicable Coding Standards. See the section related to the use of braces.
Incorrect if (var1 < var2) var1 = var2; case 5: var1 = var2; break; var1 = 5; var2 = 6; var3 = 7; var1 = var2 = var3 = 0; |
Correct if (var1 < var2) { var1 = var2; } case 5: { var1 = var2; } break; var1 = 5; var2 = 6; var3 = 7; var1 = 0; var2 = 0; var3 = 0; |
Coding Standard:
Incorrect struct something_s *x = (struct something_s*) y; |
Correct struct something_s *x = (struct something_s *)y; |
Spaces before and after binary operators.
All binary operators (operators that come between two values), such as +
, -
, =
, !=
, ==
, >
, etc. should have a space before and after the operator, for readability. As examples:
Incorrect for=bar; if(a==b) for(i=0;i>5;i++) |
Correct for = bar; if (a == b) for (i = 0; i > 5; i++) |
No space separating unary operators.
Unary operators (operators that operate on only one value), such as ++
, should not have a space between the operator and the variable or number they are operating on.
Incorrect x ++; |
Correct x++; |
if then else
StatementCoding Standard:
if <condition>
and else
must lie on separate lines with nothing else present on the line.
if <condition>
follows the standard indentation and parentheses rules.
if
in the if <condition>
line and the else
must be aligned at the same column.
if <condition>
and else
lines must always be enclosed in braces.
Braces must follow the if <condition>
and else
lines even in the case where these is no contained statement!
Other Applicable Coding Standards. See sections related to use of braces and indentation.
Incorrect if(var1 < var2) var1 = var2; if(var > 0) var--; else var = 0; if (var1 > 0) { var1--; } else { var1 = 0; } var2 = var1; |
Correct if (var1 < var2 { var1 = var2; } if (var > 0) { var--; } else { var = 0; } if (var1 > 0) { var1--; } else { var1 = 0; } var2 = var1; |
<condition> ?
<then> :
<else>
Other Applicable Coding Standards. See sections related to parentheses.
Example int arg1 = arg2 > arg3 ? arg2 : arg3; int arg1 = ((arg2 > arg3) ? arg2 : arg3); |
switch
StatementCoding Standard:
default
case.
The default
case should always be present and trigger an error if it is reached when it should not be.
break
) be enclosed in braces.
If you need to instantiate local variables in case logic, then that logic must be surrounded with braces.
break
outside of braces.
break
statements are normally indented by two spaces.
When used conditionally with case logic, the placement of the break statement follows normal indentation rules.
Other Applicable Coding Standards. See sections related to use of braces, indentation, and comments.
Example switch (...) { case 1: /* Example of a comment following a case selector. */ ... /* Example of a comment preceding a case selector. */ case 2: { /* Example of comment following the case selector. */ int value; ... } break; default: break; } |
while
StatementCoding Standard:
while <condition>
must lie on a separate line with nothing else present on the line.
while <condition>
follows the standard indentation and parentheses rules.
while <condition>
must always be enclosed in braces, even if only a single statement follows.
while <condition>
.
The single semicolon (null statement) is sufficient;
Other Applicable Coding Standards. See sections related to use of braces, indentation, and comments.
Incorrect while( notready() ) { } ready = true; while (*ptr != '\0') ptr++; |
Correct while (notready()); ready = true; while (*ptr != '\0') { ptr++; } |
do while
StatementCoding Standard:
do
and while <condition>
must lie on separate lines with nothing else present on the line.
do .. while <condition>
follows the standard indentation and parentheses rules.
do
must always be enclosed in braces, even if only a single statement follows.
Other Applicable Coding Standards. See sections related to use of braces, indentation, and comments.
Incorrect do { ready = !notready(); } while (!ready); senddata(); do ptr++; while (*ptr != '\0'); |
Correct do { ready = !notready(); } while (!ready); senddata(); do { ptr++; } while (*ptr != '\0'); |
goto
Coding Standard:
goto
.
All use of the goto
statement is prohibited except for one usage:
for handling error conditions in complex, nested logic.
A simple goto
in those conditions can greatly improve the readability and complexity of the code.
_
is permitted to break up long labels.
errout
.
Multiple error labels are often to required to unwind to recover resources committe in logic prior to the error to otherwise undo preceding operations.
Naming for these other labels would be some like errout_with_allocation
, errout_with_openfile
, etc.
Example FAR struct some_struct_s *ptr; int fd; int ret; ... if (arg == NULL) { ret = -EINVAL; goto errout; } ... ptr = (FAR struct some_struct_s *)malloc(sizeof(struct some_struct_s)); if (!ptr) { ret = -ENOMEM; goto errout; } ... fd = open(filename, O_RDONLY); if (fd < 0) { errcode = -errno; DEBUGASSERT(errcode > 0); goto errotout_with_alloc; } ... ret = readfile(fd); if (ret < 0) { goto errout_with_openfile; } ... errout_with_openfile: close(fd); errout_with_alloc: free(ptr); error: return ret; |
NOTE:
See the discussion of pointers for information about the FAR
qualifier used above.
Appendix A |
/**************************************************************************** * <Relative path to the file> * <Optional one line file description> * * Copyright (C) <Year> <Copyright holder's name>. All rights reserved. * Author: <Author's name> <Contact e-mail> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/
All header files are included here.
/**************************************************************************** * Pre-processor Definitions ****************************************************************************/
All C pre-processor macros are defined here.
/**************************************************************************** * Private Types ****************************************************************************/
Any types, enumerations, structures or unions used by the file are defined here.
/**************************************************************************** * Private Function Prototypes ****************************************************************************/
Prototypes of all static functions in the file are provided here.
/**************************************************************************** * Private Data ****************************************************************************/
All static data definitions appear here.
/**************************************************************************** * Public Data ****************************************************************************/
All data definitions with global scope appear here.
/**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: <Static function name> * * Description: * Description of the operation of the static function. * * Input Parameters: * A list of input parameters, one-per-line, appears here along with a * description of each input parameter. * * Returned Value: * Description of the value returned by this function (if any), * including an enumeration of all possible error values. * * Assumptions/Limitations: * Anything else that one might need to know to use this function. * ****************************************************************************/
All static functions in the file are defined in this grouping. Each is preceded by a function header similar to the above.
/**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: <Global function name> * * Description: * Description of the operation of the function. * * Input Parameters: * A list of input parameters, one-per-line, appears here along with a * description of each input parameter. * * Returned Value: * Description of the value returned by this function (if any), * including an enumeration of all possible error values. * * Assumptions/Limitations: * Anything else that one might need to know to use this function. * ****************************************************************************/
All global functions in the file are defined here.
/**************************************************************************** * <Relative path to the file> * <Optional one line file description> * * Copyright (C) <Year> <Copyright holder's name>. All rights reserved. * Author: <Author's name> <Contact e-mail> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/
Header file idempotence definitions go here
/**************************************************************************** * Included Files ****************************************************************************/
All header files are included here.
/**************************************************************************** * Pre-processor Definitions ****************************************************************************/
All C pre-processor macros are defined here.
/**************************************************************************** * Public Types ****************************************************************************/ #ifndef __ASSEMBLY__
Any types, enumerations, structures or unions are defined here.
/**************************************************************************** * Public Data ****************************************************************************/ #ifdef __cplusplus #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif
All data declarations with global scope appear here, preceded by the definition EXTERN
.
/**************************************************************************** * Inline Functions ****************************************************************************/ /**************************************************************************** * Name: <Inline function name> * * Description: * Description of the operation of the inline function. * * Input Parameters: * A list of input parameters, one-per-line, appears here along with a * description of each input parameter. * * Returned Value: * Description of the value returned by this function (if any), * including an enumeration of all possible error values. * * Assumptions/Limitations: * Anything else that one might need to know to use this function. * ****************************************************************************/
Any static inline functions may be defined in this grouping. Each is preceded by a function header similar to the above.
/**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: <Global function name> * * Description: * Description of the operation of the function. * * Input Parameters: * A list of input parameters, one-per-line, appears here along with a * description of each input parameter. * * Returned Value: * Description of the value returned by this function (if any), * including an enumeration of all possible error values. * * Assumptions/Limitations: * Anything else that one might need to know to use this function. * ****************************************************************************/
All global functions in the file are prototyped here. The keyword extern
or the definition EXTERN
are never used with function prototypes.
#undef EXTERN #ifdef __cplusplus } #endif #endif /* __INCLUDE_ASSERT_H */
Ending with the header file idempotence #endif
.