搞C语言开发的想必听过pc lint的大名(没听过的只能说明你的code达不到ANSI C的标准哦~)
但是那个是windows环境下面的工具了,如果我是用ubuntu来做C语言开发的怎么办?不用担心啦,现在有一款类似的工具可以解决你的问题,也就是本文要说的splint,具体安装方法:
sudo apt-get install splint
其他平台以此类推哈,我在这里贴一个gcc能build过的例子:
#include <stdio.h>
void main()
{
char *p = NULL;
char a[5] = "abc";
int b = 'a';
}
运行的结果:
cheny.le@cheny-ThinkPad-T420:~$ gcc h.c
cheny.le@cheny-ThinkPad-T420:~$ ./a.out
cheny.le@cheny-ThinkPad-T420:~$
看起来是正常的哈。
我们用splint来扫一下看是什么情况:
cheny.le@cheny-ThinkPad-T420:~$ splint h.c
Splint 3.1.2 --- 03 May 2009
h.c:3:6: Function main declared to return void, should return int
The function main does not match the expected type. (Use -maintype to inhibit
warning)
h.c: (in function main)
h.c:7:13: Variable b initialized to type char, expects int: 'a'
A character constant is used as an int. Use +charintliteral to allow
character constants to be used as ints. (This is safe since the actual type
of a char constant is int.)
h.c:5:11: Variable p declared but not used
A variable is declared but never used. Use /*@unused@*/ in front of
declaration to suppress message. (Use -varuse to inhibit warning)
h.c:6:10: Variable a declared but not used
h.c:7:9: Variable b declared but not used
Finished checking --- 5 code warnings
5个warnings哈,说明这么一小段code,写法是十分不符合标准的。
再加大力度扫描一下:
cheny.le@cheny-ThinkPad-T420:~$ splint -strict h.c
Splint 3.1.2 --- 03 May 2009
h.c:3:6: Function main declared to return void, should return int
The function main does not match the expected type. (Use -maintype to inhibit
warning)
h.c:3:6: Function main declared without parameter list
A function declaration does not have a parameter list. (Use -noparams to
inhibit warning)
h.c: (in function main)
h.c:6:17: String literal with 4 characters is assigned to char [5] (possible
waste of storage): "abc"
A string literal is assigned to a char array that smaller than the string
literal needs. (Use -stringliteralsmaller to inhibit warning)
h.c:7:13: Variable b initialized to type char, expects int: 'a'
A character constant is used as an int. Use +charintliteral to allow
character constants to be used as ints. (This is safe since the actual type
of a char constant is int.)
h.c:5:11: Variable p declared but not used
A variable is declared but never used. Use /*@unused@*/ in front of
declaration to suppress message. (Use -varuse to inhibit warning)
h.c:6:10: Variable a declared but not used
h.c:7:9: Variable b declared but not used
Finished checking --- 7 code warnings
7个warnings哈,warnings数量跟代码的行数差不多了,已经到了令人发指的地步了。
大致解释一下:
(1)main函数返回值不允许为void
(2)main函数的函数列表如果是空的话必须加上void,否则就要使用int main(int argc, char *argv[])的参数列表了
(3)数组空间浪费,只需要使用4个字节的长度就可以(真贴心)
(4)int型的变量给赋了一个char型的值,虽然类型是兼容的,但是不建议这么做
(5)(6)(7)变量p,b,a都定义了,但是没有使用(一般来说正常的code不会有这样子的问题的,不然就是浪费空间了)
要想学习好C语言,就不要放过每个warning,用splint工具扫一下你的程序,保证你能在短时间内学习到很多C语言知识!