• 注册 / 登录
  • 切换到窄版
  • 查看: 2763|回复: 0

    如何让自己写的C语言编程规范

    [复制链接]

    665

    主题

    679

    帖子

    6476

    积分

    版主

    Rank: 7Rank: 7Rank: 7

    积分
    6476
    发表于 2022-3-29 14:54:00 | 显示全部楼层 |阅读模式

    路线栈欢迎您!

    您需要 登录 才可以下载或查看,没有帐号?立即注册

    x
    今天给大家分享一篇C语言编码规范,可以从源头上规避掉很多bug,希望能对大家有所帮助。

    一、最重要的规则

    编写代码时最重要的一条规则是:检查周围的代码并尝试模仿它。

    作为维护人员,如果收到的补丁明显与周围代码的编码风格不同,这是令人沮丧的。这是不尊重人的,就像某人穿着泥泞的鞋子走进一间一尘不染的房子。

    因此,无论本文推荐的是什么,如果已经编写了代码并且您正在对其进行修补,请保持其当前的样式一致,即使它不是您最喜欢的样式。

    二、一般性的规则

    这里列出了最明显和最重要的一般规则。在你继续阅读其他章节之前,请仔细检查它们:
    • 使用C99标准
    • 不使用制表符,而是使用空格
    • 每个缩进级别使用4个空格
    • 在关键字和左括号之间使用一个空格
    • 在函数名和左括号之间不要使用空格

    1. int32_t a = sum(4, 3);              /* OK */
    2. int32_t a = sum (4, 3);             /* Wrong */
    复制代码

    • 不要在变量/函数/宏/类型中使用_或前缀。这是为C语言本身保留的
    • 对于严格的模块私有函数,使用prv_ name前缀
    • 对于包含下划线_ char的变量/函数/宏/类型,只能使用小写字母
    • 左花括号总是与关键字(for, while, do, switch, if,…)在同一行

    1. size_t i;
    2. for (i = 0; i < 5; ++i) {           /* OK */
    3. }
    4. for (i = 0; i < 5; ++i){            /* Wrong */
    5. }
    6. for (i = 0; i < 5; ++i)             /* Wrong */
    7. {
    8. }
    复制代码

    • 在比较操作符和赋值操作符之前和之后使用单个空格

    1. int32_t a;
    2. a = 3 + 4;              /* OK */
    3. for (a = 0; a < 5; ++a) /* OK */
    4. a=3+4;                  /* Wrong */
    5. a = 3+4;                /* Wrong */
    6. for (a=0;a<5;++a)       /* Wrong */
    复制代码

    • 每个逗号后用单空格

    1. func_name(5, 4);        /* OK */
    2. func_name(4,3);         /* Wrong */
    复制代码

    • 不要初始化静态和全局变量为0(或NULL),让编译器为您做

    1. static int32_t a;       /* OK */
    2. static int32_t b = 4;   /* OK */
    3. static int32_t a = 0;   /* Wrong */

    4. void my_func(void) {
    5.     static int32_t* ptr;/* OK */
    6.     static char abc = 0;/* Wrong */
    7. }
    复制代码

    • 在同一行中声明所有相同类型的局部变量

    1. void my_func(void) {
    2.     char a;             /* OK */
    3.     char b;             /* Wrong, variable with char type already exists */
    4.     char a, b;          /* OK */
    5. }
    复制代码

    • 按顺序声明局部变量

           i. 自定义结构和枚举
           ii. 整数类型,更宽的无符号类型优先
           iii. 单/双浮点
    1. int my_func(void) {
    2.     /* 1 */
    3.     my_struct_t my;     /* First custom structures */
    4.     my_struct_ptr_t* p; /* Pointers too */

    5.     /* 2 */
    6.     uint32_t a;
    7.     int32_t b;
    8.     uint16_t c;
    9.     int16_t g;
    10.     char h;
    11.     /* ... */

    12.     /* 3 */
    13.     double d;
    14.     float f;
    15. }
    复制代码

    • 总是在块的开头声明局部变量,在第一个可执行语句之前
    • 在for循环中声明计数器变量

    1. /* OK */
    2. for (size_t i = 0; i < 10; ++i)

    3. /* OK, if you need counter variable later */
    4. size_t i;
    5. for (i = 0; i < 10; ++i) {
    6.     if (...) {
    7.         break;
    8.     }
    9. }
    10. if (i * 10) {

    11. }

    12. /* Wrong */
    13. size_t i;
    14. for (i = 0; i < 10; ++i) ...
    复制代码

    • 避免在声明中使用函数调用来赋值变量,除了单个变量

    1. void a(void) {
    2.     /* Avoid function calls when declaring variable */
    3.     int32_t a, b = sum(1, 2);

    4.     /* Use this */
    5.     int32_t a, b;
    6.     b = sum(1, 2);

    7.     /* This is ok */
    8.     uint8_t a = 3, b = 4;
    9. }
    复制代码

    • 除了char、float或double之外,始终使用stdint.h标准库中声明的类型。例如,8位的uint8_t等
    • 不要使用stdbool.h库。分别使用1或0表示真或假

    1. /* OK */
    2. uint8_t status;
    3. status = 0;

    4. /* Wrong */
    5. #include <stdbool.h>
    6. bool status = true;
    复制代码

    • 永远不要与真实相比较。例如,使用if(check_func()){…}替换if (check_func() * 1)
    • 总是将指针与空值进行比较

    1. void* ptr;

    2. /* ... */

    3. /* OK, compare against NULL */
    4. if (ptr * NULL || ptr != NULL) {

    5. }

    6. /* Wrong */
    7. if (ptr || !ptr) {

    8. }
    复制代码

    • 总是使用前增量(和递减),而不是后增量(和递减)

    1. int32_t a = 0;
    2. ...

    3. a++;            /* Wrong */
    4. ++a;            /* OK */

    5. for (size_t j = 0; j < 10; ++j) {}  /* OK */
    复制代码

    • 总是使用size_t作为长度或大小变量
    • 如果函数不应该修改指针所指向的内存,则总是使用const作为指针
    • 如果不应该修改函数的形参或变量,则总是使用const

    1. /* When d could be modified, data pointed to by d could not be modified */
    2. void
    3. my_func(const void* d) {

    4. }

    5. /* When d and data pointed to by d both could not be modified */
    6. void
    7. my_func(const void* const d) {

    8. }

    9. /* Not required, it is advised */
    10. void
    11. my_func(const size_t len) {

    12. }

    13. /* When d should not be modified inside function, only data pointed to by d could be modified */
    14. void
    15. my_func(void* const d) {

    16. }
    复制代码

    • 当函数可以接受任何类型的指针时,总是使用void *,不要使用uint8_t *。函数在实现时必须注意正确的类型转换

    1. /*
    2. * To send data, function should not modify memory pointed to by `data` variable
    3. * thus `const` keyword is important
    4. *
    5. * To send generic data (or to write them to file)
    6. * any type may be passed for data,
    7. * thus use `void *`
    8. */
    9. /* OK example */
    10. void send_data(const void* data, size_t len) { /* OK */
    11.     /* Do not cast `void *` or `const void *` */
    12.     const uint8_t* d = data;/* Function handles proper type for internal usage */
    13. }

    14. void send_data(const void* data, int len) {    /* Wrong, not not use int */
    15. }
    复制代码

    • 总是使用括号和sizeof操作符
    • 不要使用变长数组。使用动态内存分配代替标准C malloc和自由函数,或者如果库/项目提供了自定义内存分配,使用它的实现看看LwMEM,一个自定义内存管理库。

    1. /* OK */
    2. #include <stdlib.h>
    3. void
    4. my_func(size_t size) {
    5.     int32_t* arr;
    6.     arr = malloc(sizeof(*arr) * n); /* OK, Allocate memory */
    7.     arr = malloc(sizeof *arr * n);  /* Wrong, brackets for sizeof operator are missing */
    8.     if (arr * NULL) {
    9.         /* FAIL, no memory */
    10.     }

    11.     free(arr);  /* Free memory after usage */
    12. }

    13. /* Wrong */
    14. void
    15. my_func(size_t size) {
    16.     int32_t arr[size];  /* Wrong, do not use VLA */
    17. }
    复制代码

    • 总是将variable与0进行比较,除非它被视为布尔类型
    • 永远不要将布尔处理的变量与0或1进行比较。用NOT(!)代替

    1. size_t length = 5;  /* Counter variable */
    2. uint8_t is_ok = 0;  /* Boolean-treated variable */
    3. if (length)         /* Wrong, length is not treated as boolean */
    4. if (length > 0)     /* OK, length is treated as counter variable containing multi values, not only 0 or 1 */
    5. if (length * 0)    /* OK, length is treated as counter variable containing multi values, not only 0 or 1 */

    6. if (is_ok)          /* OK, variable is treated as boolean */
    7. if (!is_ok)         /* OK, -||- */
    8. if (is_ok * 1)     /* Wrong, never compare boolean variable against 1! */
    9. if (is_ok * 0)     /* Wrong, use ! for negative check */
    复制代码

    • 对于注释,总是使用/* comment */,即使是单行注释
    • 在头文件中总是包含带有extern关键字的c++检查
    • 每个函数都必须包含doxygen-enabled注释,即使函数是静态的
    • 使用英文名称/文本的函数,变量,注释
    • 变量使用小写字母
    • 如果变量包含多个名称,请使用下划线。force_redraw。不要使用forceRedraw
    • 对于C标准库的包含文件,请始终使用<和>。例如,# include < stdlib.h >
    • 对于自定义库,请始终使用""。例如,# include“my_library.h”
    • 当转换为指针类型时,总是将星号与类型对齐,例如。uint8_t* t = (uint8_t*)var_width_diff_type
    • 始终尊重项目或库中已经使用的代码风格


    三、注释相关的规则

    • 不允许以//开头的注释。总是使用② comment */,即使是单行注释
    • 对于多行注释,每行使用空格+星号

    1. /*
    2. * This is multi-line comments,
    3. * written in 2 lines (ok)
    4. */

    5. /**
    6. * Wrong, use double-asterisk only for doxygen documentation
    7. */

    8. /*
    9. * Single line comment without space before asterisk (wrong)
    10. */

    11. /*
    12. * Single line comment in multi-line configuration (wrong)
    13. */

    14. /* Single line comment (ok) */
    复制代码

    注释时使用12个缩进(12 * 4个空格)偏移量。如果语句大于12个缩进,将注释4-空格对齐(下面的例子)到下一个可用缩进
    1. void my_func(void) {
    2.     char a, b;

    3.     a = call_func_returning_char_a(a);          /* This is comment with 12*4 spaces indent from beginning of line */
    4.     b = call_func_returning_char_a_but_func_name_is_very_long(a);   /* This is comment, aligned to 4-spaces indent */
    5. }
    复制代码


    四、函数定义的规则

    • 每个可以从模块外部访问的函数都必须包含函数原型(或声明)
    • 函数名必须小写,可以用下划线_分隔。(这个原则好像因人而异)

    1. /* OK */
    2. void my_func(void);
    3. void myfunc(void);

    4. /* Wrong */
    5. void MYFunc(void);
    6. void myFunc();
    复制代码

    • 当函数返回指针时,将星号对齐到返回类型

    1. /* OK */
    2. const char* my_func(void);
    3. my_struct_t* my_func(int32_t a, int32_t b);

    4. /* Wrong */
    5. const char *my_func(void);
    6. my_struct_t * my_func(void);
    复制代码

    • 对齐所有的功能原型(使用相同/相似的功能)以提高可读性

    1. /* OK, function names aligned */
    2. void        set(int32_t a);
    3. my_type_t   get(void);
    4. my_ptr_t*   get_ptr(void);

    5. /* Wrong */
    6. void set(int32_t a);
    7. const char * get(void);
    复制代码

    • 函数实现必须在单独的行中包含返回类型和可选的其他关键字

    1. /* OK */
    2. int32_t
    3. foo(void) {
    4.     return 0;
    5. }

    6. /* OK */
    7. static const char*
    8. get_string(void) {
    9.     return "Hello world!\r\n";
    10. }

    11. /* Wrong */
    12. int32_t foo(void) {
    13.     return 0;
    14. }
    复制代码


    五、变量相关的规则

    • 使变量名全部小写,下划线_字符可选

    1. /* OK */
    2. int32_t a;
    3. int32_t my_var;
    4. int32_t myvar;

    5. /* Wrong */
    6. int32_t A;
    7. int32_t myVar;
    8. int32_t MYVar;
    复制代码

    • 按类型将局部变量分组在一起

    1. void foo(void) {
    2.     int32_t a, b;   /* OK */
    3.     char a;
    4.     char b;         /* Wrong, char type already exists */
    5. }
    复制代码

    • 不要在第一个可执行语句之后声明变量

    1. void foo(void) {
    2.     int32_t a;
    3.     a = bar();
    4.     int32_t b;      /* Wrong, there is already executable statement */
    5. }
    复制代码

    • 你可以在下一个缩进级别中声明新的变量

    1. int32_t a, b;
    2. a = foo();
    3. if (a) {
    4.     int32_t c, d;   /* OK, c and d are in if-statement scope */
    5.     c = foo();
    6.     int32_t e;      /* Wrong, there was already executable statement inside block */
    7. }
    复制代码

    • 用星号声明指针变量与类型对齐

    1. /* OK */
    2. char* a;

    3. /* Wrong */
    4. char *a;
    5. char * a;
    复制代码

    • 当声明多个指针变量时,可以使用星号对变量名进行声明

    1. /* OK */
    2. char *p, *n;
    复制代码


    六、结构、枚举类型定义

    • 结构名或枚举名必须小写,单词之间有下划线_字符
    • 结构或枚举可以包含typedef关键字
    • 所有结构成员都必须小写
    • 所有枚举成员必须是大写的
    • 结构/枚举必须遵循doxygen文档语法
    • 在声明结构体时,它可以使用以下三种不同的选项之一:

       1. 当结构体仅用名称声明时,它的名称后不能包含_t后缀。

    1. struct struct_name {
    2.     char* a;
    3.     char b;
    4. };
    复制代码

       2. 当只使用typedef声明结构时,它的名称后面必须包含_t后缀。

    1. typedef struct {
    2.     char* a;
    3.     char b;
    4. } struct_name_t;
    复制代码

       3. 当结构用name和typedef声明时,它不能包含t作为基本名称,它必须在它的名称后面包含t后缀作为typedef部分。

    1. typedef struct struct_name {
    2.     char* a;
    3.     char b;
    4.     char c;
    5. } struct_name_t;
    复制代码

    • 错误声明的例子及其建议的纠正:

    1. /* a and b must be separated to 2 lines */
    2. /* Name of structure with typedef must include _t suffix */
    3. typedef struct {
    4.     int32_t a, b;
    5. } a;

    6. /* Corrected version */
    7. typedef struct {
    8.     int32_t a;
    9.     int32_t b;
    10. } a_t;

    11. /* Wrong name, it must not include _t suffix */
    12. struct name_t {
    13.     int32_t a;
    14.     int32_t b;
    15. };

    16. /* Wrong parameters, must be all uppercase */
    17. typedef enum {
    18.     MY_ENUM_TESTA,
    19.     my_enum_testb,
    20. } my_enum_t;
    复制代码

    • 在声明时初始化结构时,使用C99初始化风格

    1. /* OK */
    2. a_t a = {
    3.     .a = 4,
    4.     .b = 5,
    5. };

    6. /* Wrong */
    7. a_t a = {1, 2};
    复制代码

    • 当为函数句柄引入new typedef时,使用_fn后缀

    1. /* Function accepts 2 parameters and returns uint8_t */
    2. /* Name of typedef has `_fn` suffix */
    3. typedef uint8_t (*my_func_typedef_fn)(uint8_t p1, const char* p2);
    复制代码


    七、复合语句规则

    • 每个复合语句必须包括左花括号和右花括号,即使它只包含1个嵌套语句
    • 每个复合语句必须包含单个缩进;嵌套语句时,每个嵌套包含1个缩进大小

    1. /* OK */
    2. if (c) {
    3.     do_a();
    4. } else {
    5.     do_b();
    6. }

    7. /* Wrong */
    8. if (c)
    9.     do_a();
    10. else
    11.     do_b();

    12. /* Wrong */
    13. if (c) do_a();
    14. else do_b();
    复制代码

    • 在if或if-else-if语句的情况下,else必须与第一条语句的右括号在同一行

    1. /* OK */
    2. if (a) {

    3. } else if (b) {

    4. } else {

    5. }

    6. /* Wrong */
    7. if (a) {

    8. }
    9. else {

    10. }

    11. /* Wrong */
    12. if (a) {

    13. }
    14. else
    15. {

    16. }
    复制代码

    • 在do-while语句的情况下,while部分必须与do部分的右括号在同一行

    1. /* OK */
    2. do {
    3.     int32_t a;
    4.     a = do_a();
    5.     do_b(a);
    6. } while (check());

    7. /* Wrong */
    8. do
    9. {
    10. /* ... */
    11. } while (check());

    12. /* Wrong */
    13. do {
    14. /* ... */
    15. }
    16. while (check());
    复制代码

    • 每一个开括号都需要缩进

    1. if (a) {
    2.     do_a();
    3. } else {
    4.     do_b();
    5.     if (c) {
    6.         do_c();
    7.     }
    8. }
    复制代码

    • 不要做没有花括号的复合语句,即使是单个语句。下面的例子展示了一些不好的做法

    1. if (a) do_b();
    2. else do_c();

    3. if (a) do_a(); else do_b();
    复制代码

    • 空while循环、do-while循环或for循环必须包含花括号

    1. /* OK */
    2. while (is_register_bit_set()) {}

    3. /* Wrong */
    4. while (is_register_bit_set());
    5. while (is_register_bit_set()) { }
    6. while (is_register_bit_set()) {
    7. }
    复制代码

    • 如果while(或for、do-while等)为空(嵌入式编程中也可能是这种情况),请使用空的单行括号

    1. /* Wait for bit to be set in embedded hardware unit
    2. uint32_t* addr = HW_PERIPH_REGISTER_ADDR;

    3. /* Wait bit 13 to be ready */
    4. while (*addr & (1 << 13)) {}        /* OK, empty loop contains no spaces inside curly brackets */
    5. while (*addr & (1 << 13)) { }       /* Wrong */
    6. while (*addr & (1 << 13)) {         /* Wrong */

    7. }
    8. while (*addr & (1 << 13));          /* Wrong, curly brackets are missing. Can lead to compiler warnings or unintentional bugs */
    复制代码

    • 尽量避免在循环块内递增变量,参见示例

    1. /* Not recommended */
    2. int32_t a = 0;
    3. while (a < 10) {
    4.     .
    5.     ..
    6.     ...
    7.     ++a;
    8. }

    9. /* Better */
    10. for (size_t a = 0; a < 10; ++a) {

    11. }

    12. /* Better, if inc may not happen in every cycle */
    13. for (size_t a = 0; a < 10; ) {
    14.     if (...) {
    15.         ++a;
    16.     }
    17. }
    复制代码


    八、分支语句规则

    • 为每个case语句添加单个缩进
    • 使用额外的单缩进break语句在每个case或default

    1. /* OK, every case has single indent */
    2. /* OK, every break has additional indent */
    3. switch (check()) {
    4.     case 0:
    5.         do_a();
    6.         break;
    7.     case 1:
    8.         do_b();
    9.         break;
    10.     default:
    11.         break;
    12. }

    13. /* Wrong, case indent missing */
    14. switch (check()) {
    15. case 0:
    16.     do_a();
    17.     break;
    18. case 1:
    19.     do_b();
    20.     break;
    21. default:
    22.     break;
    23. }

    24. /* Wrong */
    25. switch (check()) {
    26.     case 0:
    27.         do_a();
    28.     break;      /* Wrong, break must have indent as it is under case */
    29.     case 1:
    30.     do_b();     /* Wrong, indent under case is missing */
    31.     break;
    32.     default:
    33.         break;
    34. }
    复制代码

    • 总是包含default语句

    1. /* OK */
    2. switch (var) {
    3.     case 0:
    4.         do_job();
    5.         break;
    6.     default: break;
    7. }

    8. /* Wrong, default is missing */
    9. switch (var) {
    10.     case 0:
    11.         do_job();
    12.         break;
    13. }
    复制代码

    • 如果需要局部变量,则使用花括号并在里面放入break语句。将左花括号放在case语句的同一行

    1. switch (a) {
    2.     /* OK */
    3.     case 0: {
    4.         int32_t a, b;
    5.         char c;
    6.         a = 5;
    7.         /* ... */
    8.         break;
    9.     }

    10.     /* Wrong */
    11.     case 1:
    12.     {
    13.         int32_t a;
    14.         break;
    15.     }

    16.     /* Wrong, break shall be inside */
    17.     case 2: {
    18.         int32_t a;
    19.     }
    20.     break;
    21. }
    复制代码


    九、宏和预处理指令

    • 总是使用宏而不是文字常量,特别是对于数字
    • 所有的宏必须是全大写的,并带有下划线_字符(可选),除非它们被明确标记为function,将来可能会被常规函数语法替换

    1. /* OK */
    2. #define MY_MACRO(x)         ((x) * (x))

    3. /* Wrong */
    4. #define square(x)           ((x) * (x))
    复制代码

    • 总是用圆括号保护输入参数

    1. /* OK */
    2. #define MIN(x, y)           ((x) < (y) ? (x) : (y))

    3. /* Wrong */
    4. #define MIN(x, y)           x < y ? x : y
    复制代码

    • 总是用括号保护最终的宏计算

    1. /* Wrong */
    2. #define MIN(x, y)           (x) < (y) ? (x) : (y)
    3. #define SUM(x, y)           (x) + (y)

    4. /* Imagine result of this equation using wrong SUM implementation */
    5. int32_t x = 5 * SUM(3, 4);  /* Expected result is 5 * 7 = 35 */
    6. int32_t x = 5 * (3) + (4);  /* It is evaluated to this, final result = 19 which is not what we expect */

    7. /* Correct implementation */
    8. #define MIN(x, y)           ((x) < (y) ? (x) : (y))
    9. #define SUM(x, y)           ((x) + (y))
    复制代码

    • 当宏使用多个语句时,使用do-while(0)语句保护它

    1. typedef struct {
    2.     int32_t px, py;
    3. } point_t;
    4. point_t p;                  /* Define new point */

    5. /* Wrong implementation */

    6. /* Define macro to set point */
    7. #define SET_POINT(p, x, y)  (p)->px = (x); (p)->py = (y)    /* 2 statements. Last one should not implement semicolon */

    8. SET_POINT(&p, 3, 4);        /* Set point to position 3, 4. This evaluates to... */
    9. (&p)->px = (3); (&p)->py = (4); /* ... to this. In this example this is not a problem. */

    10. /* Consider this ugly code, however it is valid by C standard (not recommended) */
    11. if (a)                      /* If a is true */
    12.     if (b)                  /* If b is true */
    13.         SET_POINT(&p, 3, 4);/* Set point to x = 3, y = 4 */
    14.     else
    15.         SET_POINT(&p, 5, 6);/* Set point to x = 5, y = 6 */

    16. /* Evaluates to code below. Do you see the problem? */
    17. if (a)
    18.     if (b)
    19.         (&p)->px = (3); (&p)->py = (4);
    20.     else
    21.         (&p)->px = (5); (&p)->py = (6);

    22. /* Or if we rewrite it a little */
    23. if (a)
    24.     if (b)
    25.         (&p)->px = (3);
    26.         (&p)->py = (4);
    27.     else
    28.         (&p)->px = (5);
    29.         (&p)->py = (6);

    30. /*
    31. * Ask yourself a question: To which `if` statement `else` keyword belongs?
    32. *
    33. * Based on first part of code, answer is straight-forward. To inner `if` statement when we check `b` condition
    34. * Actual answer: Compilation error as `else` belongs nowhere
    35. */

    36. /* Better and correct implementation of macro */
    37. #define SET_POINT(p, x, y)  do { (p)->px = (x); (p)->py = (y); } while (0)    /* 2 statements. No semicolon after while loop */
    38. /* Or even better */
    39. #define SET_POINT(p, x, y)  do {    \   /* Backslash indicates statement continues in new line */
    40.     (p)->px = (x);                  \
    41.     (p)->py = (y);                  \
    42. } while (0)                             /* 2 statements. No semicolon after while loop */

    43. /* Now original code evaluates to */
    44. if (a)
    45.     if (b)
    46.         do { (&p)->px = (3); (&p)->py = (4); } while (0);
    47.     else
    48.         do { (&p)->px = (5); (&p)->py = (6); } while (0);

    49. /* Every part of `if` or `else` contains only `1` inner statement (do-while), hence this is valid evaluation */

    50. /* To make code perfect, use brackets for every if-ifelse-else statements */
    51. if (a) {                    /* If a is true */
    52.     if (b) {                /* If b is true */
    53.         SET_POINT(&p, 3, 4);/* Set point to x = 3, y = 4 */
    54.     } else {
    55.         SET_POINT(&p, 5, 6);/* Set point to x = 5, y = 6 */
    56.     }
    57. }
    复制代码

    • 不缩进子语句内#if语句

    1. /* OK */
    2. #if defined(XYZ)
    3. #if defined(ABC)
    4. /* do when ABC defined */
    5. #endif /* defined(ABC) */
    6. #else /* defined(XYZ) */
    7. /* Do when XYZ not defined */
    8. #endif /* !defined(XYZ) */

    9. /* Wrong */
    10. #if defined(XYZ)
    11.     #if defined(ABC)
    12.         /* do when ABC defined */
    13.     #endif /* defined(ABC) */
    14. #else /* defined(XYZ) */
    15.     /* Do when XYZ not defined */
    16. #endif /* !defined(XYZ) */
    17. 文档
    复制代码

    • 文档化的代码允许doxygen解析和通用的html/pdf/latex输出,因此正确地执行是非常重要的。
    • 对变量、函数和结构/枚举使用doxygen支持的文档样式
    • 经常使用\作为doxygen,不要使用@
    • 始终使用5x4空格(5个制表符)作为文本行开始的偏移量

    1. /**
    2. * \brief           Holds pointer to first entry in linked list
    3. *                  Beginning of this text is 5 tabs (20 spaces) from beginning of line
    4. */
    5. static
    6. type_t* list;
    复制代码

    • 每个结构/枚举成员都必须包含文档
    • 注释的开头使用12x4空格偏移量

    1. /**
    2. * \brief           This is point struct
    3. * \note            This structure is used to calculate all point
    4. *                      related stuff
    5. */
    6. typedef struct {
    7.     int32_t x;                                  /*!< Point X coordinate */
    8.     int32_t y;                                  /*!< Point Y coordinate */
    9.     int32_t size;                               /*!< Point size.
    10.                                                     Since comment is very big,
    11.                                                     you may go to next line */
    12. } point_t;

    13. /**
    14. * \brief           Point color enumeration
    15. */
    16. typedef enum {
    17.     COLOR_RED,                                  /*!< Red color. This comment has 12x4
    18.                                                     spaces offset from beginning of line */
    19.     COLOR_GREEN,                                /*!< Green color */
    20.     COLOR_BLUE,                                 /*!< Blue color */
    21. } point_color_t;
    复制代码

    • 函数的文档必须在函数实现中编写(通常是源文件)
    • 函数必须包括简要和所有参数文档
    • 如果每个参数分别为in或out输入和输出,则必须注意
    • 如果函数返回某个值,则必须包含返回形参。这不适用于void函数
    • 函数可以包含其他doxygen关键字,如note或warning
    • 在参数名和描述之间使用冒号:

    1. /**
    2. * \brief           Sum `2` numbers
    3. * \param[in]       a: First number
    4. * \param[in]       b: Second number
    5. * \return          Sum of input values
    6. */
    7. int32_t
    8. sum(int32_t a, int32_t b) {
    9.     return a + b;
    10. }

    11. /**
    12. * \brief           Sum `2` numbers and write it to pointer
    13. * \note            This function does not return value, it stores it to pointer instead
    14. * \param[in]       a: First number
    15. * \param[in]       b: Second number
    16. * \param[out]      result: Output variable used to save result
    17. */
    18. void
    19. void_sum(int32_t a, int32_t b, int32_t* result) {
    20.     *result = a + b;
    21. }
    复制代码

    • 如果函数返回枚举的成员,则使用ref关键字指定哪个成员

    1. /**
    2. * \brief           My enumeration
    3. */
    4. typedef enum {
    5.     MY_ERR,                                     /*!< Error value */
    6.     MY_OK                                       /*!< OK value */
    7. } my_enum_t;

    8. /**
    9. * \brief           Check some value
    10. * \return          \ref MY_OK on success, member of \ref my_enum_t otherwise
    11. */
    12. my_enum_t
    13. check_value(void) {
    14.     return MY_OK;
    15. }
    复制代码

    • 对常量或数字使用符号(' NULL ' => NULL)

    1. /**
    2. * \brief           Get data from input array
    3. * \param[in]       in: Input data
    4. * \return          Pointer to output data on success, `NULL` otherwise
    5. */
    6. const void *
    7. get_data(const void* in) {
    8.     return in;
    9. }
    复制代码

    • 宏的文档必须包括hideinitializer doxygen命令

    1. /**
    2. * \brief           Get minimal value between `x` and `y`
    3. * \param[in]       x: First value
    4. * \param[in]       y: Second value
    5. * \return          Minimal value between `x` and `y`
    6. * \hideinitializer
    7. */
    8. #define MIN(x, y)       ((x) < (y) ? (x) : (y))
    复制代码


    十、头/源文件

    • 在文件末尾留下一个空行
    • 每个文件都必须包括文件的doxygen注释和后跟空行的简要描述(使用doxygen时)

    1. /**
    2. * \file            template.h
    3. * \brief           Template include file
    4. */
    5.                     /* Here is empty line */
    复制代码

    • 每个文件(头文件或源文件)必须包含许可证(开始注释包括单个星号,因为doxygen必须忽略这个)
    • 使用与项目/库已经使用的相同的许可证

    1. /**
    2. * \file            template.h
    3. * \brief           Template include file
    4. */

    5. /*
    6. * Copyright (c) year FirstName LASTNAME
    7. *
    8. * Permission is hereby granted, free of charge, to any person
    9. * obtaining a copy of this software and associated documentation
    10. * files (the "Software"), to deal in the Software without restriction,
    11. * including without limitation the rights to use, copy, modify, merge,
    12. * publish, distribute, sublicense, and/or sell copies of the Software,
    13. * and to permit persons to whom the Software is furnished to do so,
    14. * subject to the following conditions:
    15. *
    16. * The above copyright notice and this permission notice shall be
    17. * included in all copies or substantial portions of the Software.
    18. *
    19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    20. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    21. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
    22. * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    23. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    24. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    26. * OTHER DEALINGS IN THE SOFTWARE.
    27. *
    28. * This file is part of library_name.
    29. *
    30. * Author:          FirstName LASTNAME <optional_email@example.com>
    31. */
    复制代码

    • 头文件必须包含保护符#ifndef
    • 头文件必须包含c++检查
    • 在c++检查之外包含外部头文件
    • 首先用STL C文件包含外部头文件,然后是应用程序自定义文件
    • 头文件必须包含其他所有头文件,以便正确编译,但不能包含更多头文件(如果需要,.c应该包含其余的头文件)
    • 头文件必须只公开模块公共变量/类型/函数
    • 在头文件中使用extern作为全局模块变量,稍后在源文件中定义它们

    1. /* file.h ... */
    2. #ifndef ...

    3. extern int32_t my_variable; /* This is global variable declaration in header */

    4. #endif

    5. /* file.c ... */
    6. int32_t my_variable;        /* Actually defined in source */
    复制代码

    • 不要把.c文件包含在另一个.c文件中
    • .c文件应该首先包含相应的.h文件,然后是其他文件,除非另有明确的必要
    • 在头文件中不包含模块私有声明
    • 头文件示例(示例中没有license)

    1. /* License comes here */
    2. #ifndef TEMPLATE_HDR_H
    3. #define TEMPLATE_HDR_H

    4. /* Include headers */

    5. #ifdef __cplusplus
    6. extern "C" {
    7. #endif /* __cplusplus */

    8. /* File content here */

    9. #ifdef __cplusplus
    10. }
    11. #endif /* __cplusplus */

    12. #endif /* TEMPLATE_HDR_H */
    复制代码

    作者:嵌入式大杂烩

    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    小黑屋|路丝栈 ( 粤ICP备2021053448号 )

    GMT+8, 2024-9-17 03:37 , Processed in 0.049752 second(s), 18 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表