总体来说就是C/C++采用相同的coding style,但是如果是编写Linux内核模块,编写完之后,用Lindent来进行标准的Linux内核代码风格的缩进。如果是java代码,则进行标准java代码的缩进。
命名风格是C代码用Linux下的命名风格,xxx_xxx_xxx;C++代码和Java代码用微软的命名方法,variable用小写字母开头,method用大写字母开头。
最后,编程时不要偷懒,要在编程之初就进行防御性编程!因为用户和程序员(包括自己)都会犯错误,所以要在自己程序中尽早的进行防御性编程,以免程序挂的时候莫名其妙。
========================================================================
coding-style-C/C++
1. Indentation
follow emacs' default indentation for source files
2. Placing Braces
if (x is true)
{
we do y
}
int function (int x)
{
body of function
}
3. Naming
c language: xxx_xxx_xxx, refer to examples in fs/*c
c++, java: follow MS style, mXXXXX, strXXXXX, objXXXX, PutXXX(), SolveXXX()
4. Functions
Functions should only do onething, and do it well.
refer to examples in fs/*c
5. Comments
Good comments explain what the file or function does, and why it does it.
/**
* my_function - does my stuff
* @my_arg: my argument
*
* Does my stuff explained.
**/
void my_function (int my_arg)
{
...
}
/**
* my_struct - short description
* @a : first member
* @b: second member
*
* Longer Description
**/
struct my_struct
{
int a;
int b;
};
6. Data structure requirements
If another thread can find your data structure, and you don't have a
reference counter on it, you almost certainly have a bug.
7. others
no typedef except for declaring function prototypes
no magic numbers
no ifdef in .c code
labled elements in initializers
==========================================================================
Tools
indent
Lindent
#!/bin/sh
PARAM="-npro -kr -i8 -ts8 -sob -l80 -ss -ncs -cp1"
RES=`indent --version`
V1=`echo $RES | cut -d' ' -f3 | cut -d'.' -f1`
V2=`echo $RES | cut -d' ' -f3 | cut -d'.' -f2`
V3=`echo $RES | cut -d' ' -f3 | cut -d'.' -f3`
if [ $V1 -gt 2 ]; then
PARAM="$PARAM -il0"
elif [ $V1 -eq 2 ]; then
if [ $V2 -gt 2 ]; then
PARAM="$PARAM -il0";
elif [ $V2 -eq 2 ]; then
if [ $V3 -ge 10 ]; then
PARAM="$PARAM -il0"
fi
fi
fi
indent $PARAM "$@"
================================================================================
format c language files
apt-get install indent
write a script Lindent, make it executable, and copy it to bin
Lindent xxx.c
Lindent *.c
==============================================================
coding-style-java
class XXX {
}
if () {
} else if () {
} else {
}
try {
} catch () {
}
我本来不是很喜欢这种编码风格,后来接触python后,发现python的强制缩进和这种风格很像。
def fun(...) :
//编写次函数模块
//由于自动缩进,最后你在编写完后press backspace,就像给这段代码加了个}