谈谈Linux内核驱动的编码风格

发表于:2015-7-17 10:42

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:wwang    来源:51Testing软件测试网原创

  一些需要注意的Coding Style
  缩进
  1、除了注释、文档和Kconfig之外,使用Tab缩进,而不是空格,并且Tab的宽度为8个字符;
  2、switch … case …语句中,switch和case具有相同的缩进(参考上文);
  花括号
  3、花括号的使用参考K&R风格。
  如果是函数,左花括号另起一行:
  int function(int x)
  {
  body of function
  }
  否则,花括号紧接在语句的最后:
  if (x is true) {
  we do y
  }
  如果只有一行语句,则不需要用花括号:
  if (condition)
  action();
  但是,对于条件语句来说,如果一个分支是一行语句,另一个分支是多行,则需要保持一致,使用花括号:
  if (condition) {
  do_this();
  do_that();
  } else {
  otherwise();
  }
  空格
  4、在关键字“if, switch, case, for, do, while”之后需要加上空格,如:
  if (something)
  5、在关键字“sizeof, typeof, alignof, or __attribute__”之后不要加空格,如:
  sizeof(struct file)
  6、在括号里的表达式两边不要加空格,比如,下面是一个反面的例子:
  sizeof( struct file )
  7、大多说的二元和三元运算符两边需要空格,如“= + – < > * / % | & ^ <= >= == != ? :”;
  8、一元运算符后面不要空格,如“& * + – ~ ! sizeof typeof alignof __attribute__ defined”;
  9、在前缀自增自减运算符之后和后缀自增自减运算符之前不需要空格(“++”和“–”);
  10、结构成员运算符(“.”和“->”)的两边不需要空格;
  11、行尾不需要空格;
  注释
  12、使用C89的“/* … */”风格而不是C99的“// …”风格;
  13、对于多行注释,可以参考下例:
  /*
  * This is the preferred style for multi-line
  * comments in the Linux kernel source code.
  * Please use it consistently.
  *
  * Description: A column of asterisks on the left side,
  * with beginning and ending almost-blank lines.
  */
  Kconfig
  14、“config”定义下面的语句用Tab缩进,help下面的语句再额外缩进两个空格,如:
  config AUDIT
  bool "Auditing support"
  depends on NET
  help
  Enable auditing infrastructure that can be used with another
  kernel subsystem, such as SELinux (which requires this for
  logging of avc messages output). Does not do system-call
  auditing without CONFIG_AUDITSYSCALL.
  宏
  15、多行的宏定义需要用“do .. while”封装,如:
  #define macrofun(a, b, c) \
  do { \
  if (a == 5) \
  do_this(b, c); \
  } while (0)
  函数返回值
  16、函数返回值的定义最好也要遵循一定的章法。
  如果函数的名称是一种动作或者命令式的语句,应该以错误代码的形式返回(通常是0表示成功,-Exxx这种形式的负数表示错误),如:
  do_something()
  如果函数的名称是判断语句,则返回值应该类似与布尔值(通常1表示成功,0表示错误),如:
  something_is_present()
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号