我们来看一段无聊的代码(文件名为print_msg.c):
void print_msg(int a)
{
switch (a) {
case 1:
printf("a == 1\n");
break;
case 2:
printf("a == 2\n");
break;
}
}
这段代码的coding style是否有问题呢?用checkpatch.pl来检查一下:
scripts/checkpatch.pl -f print_msg.c
检查的结果是:
ERROR: switch and case should be at the same indent
#3: FILE: switch.c:3:
+ switch (a) {
+ case 1:
[...]
+ case 2:
total: 1 errors, 0 warnings, 12 lines checked
switch.c has style problems, please review. If any of these errors
are false positives report them to the maintainer, see
CHECKPATCH in MAINTAINERS.
在Linux内核的coding style里,switch和case要求有相同的缩进。本例的代码很少,错误也只有这一个,手动修改很方便。如果类似的缩紧错误很多怎么办?
sed ‘s/[ \t]*$//g’ your_code.c
一些需要注意的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)
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)