您的位置:首页 > 运维架构 > Linux

Linux 内核驱动的编码风格

2016-11-07 21:08 183 查看
不可否认,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()


参考文献: http://begeek.cn/post/7882.html?ref=myread
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux