簡介
檢查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
這一步也不是很精確, 會導致一些未用的函數被忽略掉,可以再進一步人工排查後確定未調用的函數。
作者:帥得不敢出門 轉載請註明出處