简介
检查unused的代码没有完美的解决方案,介绍比较多的是代码覆盖率检查工具,不能通过直接分析代码得到,需要代码运行起来。
静态代码检查的方式介绍比较少,这里推荐一种,那就是使用cppcheck工具
代码
test.h
#ifndef __TEST_H__
#define __TEST_H__
void Test();
int Func();
#endif /*__TEST_H__*/
test.cpp
#include "test.h"
void Test()
{
}
int Func()
{
}
main.cpp
#include "test.h"
void *ThreadFunc(void *arg)
{
Test();
}
int main(int argc, char **argv)
{
return 0;
}
使用
#cppcheck --enable=unusedFunction --force ./
Checking main.cpp …
1/2 files checked 69% done
Checking test.cpp …
2/2 files checked 100% done
[test.cpp:7]: (style) The function ‘Func’ is never used.
[main.cpp:3]: (style) The function ‘ThreadFunc’ is never used.
这里代码比较简单,cppcheck可以精准地查找到未使用的函数,如果是大的工程,会有误报,
如果想进一步筛查,可以写个shell脚本来处理
筛查
find_unused.sh
#!/usr/bin/sh
if [[ ! $# -eq 2 ]]; then
echo -e "usage $0 [unused.txt src_dir]"
echo -e "查找未使用的函数,比如:$0 unusedTxt cutedevice/src"
exit -1
fi
unusedTxt=$1
srcDir=$2
if [[ ! -f $unusedTxt ]]; then
echo -e "$unusedTxt not exists"
exhit -1
fi
if [[ ! -d $srcDir ]]; then
echo -e "$srcDir not exists"
exhit -1
fi
total=0
for thenFunction in `cat $1 | cut -d "'" -f 2`;
do
count=`find $srcDir -name "*.cpp" -o -name "*.c" | xargs grep $thenFunction | wc -l`
if [[ $count -le 1 ]]; then
echo "$thenFunction"
total=$(expr $total + 1)
fi
done
echo "unused total:$total"
第一步使用cppcheck粗确地打印未调用的函数
#cppcheck --enable=style,unusedFunction --force ./src
得到类似[src/base/utility.cpp:486]: (style) The function ‘Xor’ is never used.
将其写到unused.txt中
然后调用此脚本进行筛选, ./find_unused.sh ./unused.txt ./src
这一步也不是很精确, 会导致一些未用的函数被忽略掉,可以再进一步人工排查后确定未调用的函数。
作者:帅得不敢出门 转载请注明出处