第3章(2) Linux下C编程风格

Linux内核编码风格在内核源代码的Documentation/CodingStyle目录下(新版本内核在Documentation/process/coding-style.rst)。

  1. 变量命名采用下划线分割单词,如:
    int min_value;
    void send_data(void);
    ```  
2. 代码缩进使用“TAB”,并且Tab的宽度为**8个字符**
3. switch和case对其,即case前不缩进,如:
```C
    switch (suffix) {
    case 'G':
    case 'g':
            mem <<= 30;
            break;
    case 'M':
    case 'm':
            mem <<= 20;
            break;
    case 'K':
    case 'k':
            mem <<= 10;
            /* fall through */
    default:
            break;
    }
    ```
4. 不要把多个语句放一行,如:
```C
    if (condition) do_this;  // 不推荐
    
    if (condition) 
            do_this;  // 推荐
    ```
5. 一行不要超过80个字符,字符串实在太长,请这样:
```C
    void fun(int a, int b, int c)
    {
            if (condition)
                    printk(KERN_WARNING "Warning this is a long printk with "
                           "3 parameters a: %u b: %u "
                           "c: %u \n", a, b, c);
            else
                    next_statement;
    }
    ```
6. 代码使用K&R风格,非函数的花括号不另起一行,函数花括号另起一行,例如
```C
    if (a == b) {
        a = c;
        d = a;
    }

    int func(int x)
    {
            ;  // statements
    }
    ```
    ![](https://img2018.cnblogs.com/blog/1365872/201907/1365872-20190702170252800-2034093122.jpg)


7. do...while语句中的while和if...else语句中的else,跟“}”一行,如:
```C
    do {
            body of do-loop
    } while (condition);
    
    if (x == y) {
            ...
    } else if (x > y) {
            ...
    } else {
            ....
    }
    ```
8. 只有一条语句时不加“{ }”,但如果其他分支有多条语句,请给每个分支加“{}”,如:
```C
    if (condition)
            action();
    
    if (condition)
            do_this();
    else
            do_that();
    
    if (condition) {
            do_this();
            do_that();
    } else {
            otherwise();
    }
    
    while (condition) {
            if (test)
                    do_something();
    }
    ```
9. `if, switch, case, for, do, while`后加一个空格
10. 函数长度不要超过48行(除非函数中的switch有很多case);函数局部变量不要超过10个;函数与函数之间要空一行
posted @ 2019-07-02 15:20  Raina_R  阅读(329)  评论(0)    收藏  举报