2023年11月29日发(作者:)

Cpplint

google推出的C++编码规范检查工具(python脚本)

/p/google-styleguide/ 这是google使用的一个C++

代码风格规范,可以作为平常开发的参考。

Cpplint用法比较简单,首先系统需要安装python工具,然后把

放在项目目录下,再进入命令行,它的的语法结构如下:

Syntax: cpplint.py [ -- verbose= #] [ -- output= vs7] [ -- filter=- x

,+ y,...]

[ -- counting= total| toplevel| detailed]

< file> [ file] ...

cpplint对于发现的每一个问题, 都会给出一个位于区间[1, 5]之间的置信度评

, 分数越高就代表问题越肯定. 你可以通过verbose选项控制输出哪些级别.

如果代码中有些部分不希望被检查, 或者你认为cpplint产生了误报, 只需要

在行尾添加注释 ‘// NOLINT’, cpplint就会跳过这些行. 如果你想过滤掉特

定的警告, 就需要设置filter选项了(-表示不输出, +表示输出), 比如:

Examples: -- filter=- whitespace,+ whitespace/ braces

-- filter= whitespace,runtime/ printf,+ runtime/ printf_format

-- filter=- ,+ build/ include_what_you_use

cpplint的输出格式有’emacs’和’vc7′两种, 默认是’emacs’.

cpplint只分析.cc, cpp .h文件, 一次可以分析一到多个

以下是我自己在hisi-v7300libpng文件里找了个.h文件分析了下代码

规范,所得出的结果。

root@ubuntu11:/file/statsvninput/hisi-v7300/libpng#python

/home/kes/my-app/src/main/ -verbose=5 --output=vs7

--filter=-whitespace,-readability,-legal pngconf.h

pngconf.h(20): #ifndef header guard has wrong style, please use:

LIBPNG_PNGCONF_H_ [build/header_guard] [5]

pngconf.h(1665): #endif line should be "#endif // LIBPNG_PNGCONF_H_"

[build/header_guard] [5]

pngconf.h(1642): Never use sprintf. Use snprintf instead.

[runtime/printf] [5]

pngconf.h(1643): Never use sprintf. Use snprintf instead.

[runtime/printf] [5]

pngconf.h(1645): Never use sprintf. Use snprintf instead.

[runtime/printf] [5]

Done processing pngconf.h

Total errors found: 5

这个工具有个麻烦的地方就是,等它分析的错误结果出来之后,每个错误

行你都要回到源码里一个个去找,修改完一行错误要保存退出来,再找错误行,

再进去修改,这样反反复复,比较麻烦,网上有人写了个简单的脚本,直接把错

误信息当成注释 一次放入 源文件中,然后只需要打开一次源文件,依次修改,改

完成之后,再调用清理注释接口,删除之前插入的内容.整个过程一气呵成

#!/bin/bash

#

# add the error info to source file from

# after file is modified, clean the error info

# @

#

if [ "$1" == "-h" -o $# -eq 0 ];then

echo "Clean comment: cpplint -c file1 file2 ..."

echo " Gen comment: cpplint file1 file2 ..."

exit 1

fi

# clean the comment

if [[ "$1" == "-c" ]];then

shift 1

for file in $(ls $@);do

sed -i "/CPPLINT/d" ${file}

done

exit 1

${file} 2> tmp

cat tmp | grep "^${file}" |grep -v "copyright message found"

| awk 'BEGIN{FS=":";OFS=":"}{print $2,$3}' | sort -t: -n

-k1 >${file}.lint

IFS=':'

num=0

while read line_no comment; do