C 编程风格规范

C 编程风格规范

  • identation
    • 使用 4 个空格(不用 tab,因为 tab 宽度不一致,并且 diff 工具更易阅读)
  • brace
    • if, while 左花括号在同一行
    • 函数定义,类定义,在下一行
  • 变量名
    • 类名:FooBarCPU
    • 成员:barVariable
    • 局部变量:new_value
  • include
    • 先 main header file(和 cc 文件名相同的头文件)
    • 然后按字典顺序(为了容易找到重复 include)
  • document

    • Doxygen:自动生成文档

      Doxygen allows users to quickly create documentation for our code by extracting the relavent information from the code and comments. It is able to document all the code structures including classes, namespaces, files, members, defines, etc.

    • javadoc comment:以两个*开头的 C 风格注释

      /**
       * This is the brief description. This is the start of the detailed
       * description. Detailed Description continued.
       */
      
    • 例子

      /**
       * @file
       * Contains an example of documentation style.
       */
      
      #include <vector>
      
      /**
       * Adds two numbers together.
       */
      #define DUMMY(a,b) (a+b)
      
      /**
       * A simple class description. This class does really great things in detail.
       *
       * @todo Update to new statistics model.
       */
      class foo
      {
        /** This variable stores blah, which does foo and has invariants x,y,z
               @warning never set this to 0
               @invariant foo
          */
         int myVar;
      
       /**
        * This function does something.
        * @param a The number of times to do it.
        * @param b The thing to do it to.
        * @return The number of times it was done.
        *
        * @sa DUMMY
        */
       int bar(int a, long b);
      
      
       /**
        * A function that does bar.
        * @retval true if there is a problem, false otherwise.
        */
       bool manchu();
      
      };
      
  • 代码
    • C 文件中不该有 extern 声明,而应该通过包含头文件方式

      The key here is that we have a single external declaration in the .hh file that the compiler will automatically check for consistency with the .cc file. (This isn’t as important in C++ as it was in C, since linker name mangling will now catch these errors, but it’s still a good idea.)