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

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

  1. 变量命名采用下划线分割单词,如:oop

    int min_value;
     void send_data(void);
  2. 代码缩进使用“TAB”,而且Tab的宽度为8个字符
  3. switch和case对其,即case前不缩进,如:this

    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. 不要把多个语句放一行,如:编码

    if (condition) do_this;  // 不推荐
    
     if (condition) 
             do_this;  // 推荐
  5. 一行不要超过80个字符,字符串实在太长,请这样:code

    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风格,非函数的花括号不另起一行,函数花括号另起一行,例如blog

    if (a == b) {
         a = c;
         d = a;
     }
    
     int func(int x)
     {
             ;  // statements
     }

  7. do...while语句中的while和if...else语句中的else,跟“}”一行,如:字符串

    do {
             body of do-loop
     } while (condition);
    
     if (x == y) {
             ...
     } else if (x > y) {
             ...
     } else {
             ....
     }
  8. 只有一条语句时不加“{ }”,但若是其余分支有多条语句,请给每一个分支加“{}”,如:it

    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个;函数与函数之间要空一行io

相关文章
相关标签/搜索