NuttX C Coding Standard

Last Updated: June 18, 2017



Table of Contents

1.0 General Organization

1.1 File 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:

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:

  1. Included Files
  2. Pre-processor Definitions
  3. Private Types (definitions)
  4. Private Function Prototypes (declarations)
  5. Private Data (definitions)
  6. Public Data (definitions)
  7. Private Functions (definitions)
  8. Public Functions (definitions)

The following groupings should appear in all C header files in the following order:

  1. Included Files
  2. Pre-processor Definitions
  3. Public Types (definitions)
  4. Public Data (declarations)
  5. Inline Functions (definitions)
  6. Public Function Prototypes (declarations)

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.

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.

1.2 Lines

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.

1.3 Comments

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 exceptions are (1) for the file header block comment that begins on line one; there is no preceding blank line in that case. And (2) for conditional compilation. Conditional compilation should include the conditional logic and all comments associated with the conditional logic. In this case, the blank line appears before the conditional, not after it.

Incorrect

      /* set a equal to b */
      a = b;
      /* set b equal to c */
      b = c;
    
      /* Do the impossible */
    
    #ifdef CONFIG_THE_IMPOSSIBLE
      the_impossible();
    #endif
    

Correct

    
      /* Set a equal to b. */
    
      a = b;
    
      /* Set b equal to c. */
    
      b = c;
    
    #ifdef CONFIG_THE_IMPOSSIBLE
      /* Do the impossible */
    
      the_impossible();
    #endif
    

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 ...
    }
    

1.4 Braces

Coding Standard:

Incorrect

    while (true)
      {
        if (valid)
          {
          ...
          } /* if valid */
        else
          {
          ...
          } /* not valid */
      } /* end forever */
    if (a < b) {
      if (a < 0) {
          c = -a;
      } else {
          c = a;
      }
    } else {
      if (b < 0) {
          c = -b;
      } else {
          c = b;
      }
    }
    

Correct

    while (true)
      {
        if (valid)
          {
          ...
          }
        else
          {
          ...
          }
      }
    
    if (a < b)
      {
        if (a < 0)
          {
            c = -a;
          }
        else
          {
            c = a;
          }
      }
    else
      {
        if (b < 0)
          {
            c = -b;
          }
        else
          {
            c = b;
          }
      }
    
    

Exception to Indentation Rule for Braces. 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)
    {
      ...
    }
    
    

1.5 Indentation

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 */
    

1.6 Parentheses

Coding Standard:

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

2.1 One Definition/Declaration Per Line

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.

2.2 Global Variables

Global vs. Local vs. Public vs. Private By a global variable it is meant any variable defined outside of a function. The distinction is between this kind of global and function local definition and refers to the scope a symbol within a file. A related concept for all global names defined within a file is the scope of the name across different files. If the global symbol is pre-pended with the static storage class then the scope of the global symbol is within the file only. This is a somewhat different concept and within NuttX you will find these distinguished as private vs. public global symbols. However, within this standard, the term global variable will refer to any variable that has more than local scope.

Coding Standard:

Incorrect

    extern int someint;
    static int anotherint;
    uint32_t dwA32BitInt;
    uint32_t gAGlobalVariable;
    

Acceptable

    extern int g_someint;
    static int g_anotherint;
    uint32_t g_a32bitint;
    uint32_t g_aglobal;
    

Preferred

    struct my_variables_s
    {
      uint32_t a32bitint;
      uint32_t aglobal;
    };
    
    extern int g_someint;
    static int g_anotherint;
    struct my_variables_s g_myvariables;
    

2.3 Parameters and Local Variables

Coding Standard:

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.

2.4 Type Definitions

Coding Standard:

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.

2.5 Structures

Structure Naming

Structure Field Naming

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       /* Un-named structure */
    {
      ...
      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 */
      ...
    };
    
    struct abc_s
    {
      ...
      struct
      {
        int a;           /* Value A */
        int b;           /* Value B */
        int c;           /* Value C */
      };                 /* Un-named structure field */
      ...
    };
    
    

    Correct

    struct xyz_info_s
    {
      ...
      int val1;          /* Value 1 */
      int val2;          /* Value 2 */
      int val3;          /* Value 3 */
      ...
    };
    

    Discouraged

    typedef struct xyz_info_s xzy_info_t;
    

    The use of typedef'ed structures is acceptable but discouraged.

    Correct

    struct xyz_info_s
    {
      ...
      uint8_t bita : 1,  /* Bit A */
      uint8_t bitb : 1,  /* Bit B */
      uint8_t bitc : 1,  /* Bit C */
      ...
    };
    

    Discouraged

    struct abc_s
    {
      ...
      struct
      {
        int a;           /* Value A */
        int b;           /* Value B */
        int c;           /* Value C */
      } abc;
      ...
    };
    

    The use of structures defined within other structures is acceptable provided that they define named fields. The general practice of defining a structure within the scope of another structure, however, is still but discouraged in any case. The following is preferred:

    Preferred

    struct abc_s
    {
      ...
      int a;             /* Value A */
      int b;             /* Value B */
      int c;             /* Value C */
      ...
    };
    
    

2.6 Unions

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  /* All unions must be named */
    {
      uint8_t  b[4];   /* Byte values. */
      uint16_t h[2];   /* Half word values. */
      uint32_t w;      /* Word Value. */
    };
    
    typedef union xyz_union_u xzy_union_t;
    

    The use of typedef'ed unions is acceptable but discouraged.

    struct xyz_info_s
    {
      ...
      union
      {
        uint8_t  b[4]; /* Byte values. */
        uint16_t h[2]; /* Half word values. */
        uint32_t w;    /* Word Value. */
      } u;             /* All union fields must be named */
      ...
    };
    
    

NOTE: Note that the union fields within structures are often named u. 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 of the union value from being excessively long.

2.7 Enumerations

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.

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. */
    };
    

2.8 C Pre-processor Macros

Coding Standard:

Macro Naming. Macro naming following a naming convention similar to the naming of enumeration values.

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)
    

2.9 Pointer Variables

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).

2.10 Initializers

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

3.1 Function Headers

Coding Standard:

Function header template. Refer to Appendix A for the template for a function header.

3.2 Function Naming

Coding Standard:

3.3 Parameter Lists

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.

3.4 Function Body

Coding Standard:

Returned Values

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

4.1 One Statement Per Line

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;
    

4.2 Casts

Coding Standard:

Incorrect

    struct something_s *x = (struct something_s*) y;
    

Correct

    struct something_s *x = (struct something_s *)y;
    

4.3 Operators

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++;
    

Forbidden Multicharacter Forms. Many operators are expressed as a character in combination with = such as +=, >=, >>=, etc. Some compilers will accept the = at the beginning or the end of the sequence. This standard, however, requires that the = always appear last in order to avoid amiguities that may arise if the = were to appear first. For example, a =++ b; could also be interpreted as a =+ +b; or a = ++b all of which are very different.

4.4 if then else Statement

Coding Standard:

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);
    

4.5 switch Statement

Definitions:

Coding Standard:

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;
        }
    

4.6 while Statement

Coding Standard:

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++;
        }
    
    

4.7 do while Statement

Coding Standard:

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');
    
    

4.8 Use of goto

Coding Standard:

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

A.1 C Source File Structure

/****************************************************************************
 * <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.

A.2 C Header File Structure

/****************************************************************************
 * <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.