【编程基础】CppLint工具使用过程

前言

coding最好要形成一定的编程风格,一般常用的开源风格有google code style,可以使用cpplint工具检查是否符合该编程风格。

目录

1. linux系统使用过程;

2. windows系统使用过程;

注意,目前cpplint.py是基于python2的脚本,若要使用python3请按照python3改写cpplint.py。

操作

1. linux系统使用过程

1.1 安装cpplint;

$pip install cpplint

1.2 保存cpplint.py文件;

1.3 检测单个文件;

cpplint_dir$python2 cpplint.py test.cpp

1.4 检测批量文件;

根据要检测的文件编写shell脚本,然后运行即可。

注意,sh和bat适应于不同的系统,bat文件是window系统的执行文件,sh是linux系统的批处理文件。

cpplint_shell.sh实例;

#! /bin/bash
echo "^@^cpplint code style check through shell====^@^"
index=0
config=""
pwd_path=`pwd`
cpplint_path="$pwd_path/cpplint.py"
echo cpplint_path=$cpplint_path

src_path="$pwd_path/src"
echo src_path=$src_path
# add file to an array,and check file in array last
# for file in `find $src_path -name "*.h" -type f`
for file in `find $src_path -maxdepth 1 -type f | grep -E ".h$|.cc$|.cu$|.cpp$"`
do
    echo file=$file
    echo -e "33[36m ===> [FILE] 33[0m 33[47;31m $file 33[0m"
    check_files[$index]=$file
    index=$(($index+1))
done
# accroding to config options make a checking command
# first check if python2 exists
check_cmd=""
is_python2_exists=`ls /usr/bin/ | grep -E '^python2$' | wc -l`
if [ $is_python2_exists -ge 1 ]
then
    # read cpplint.ini to decide which option to add
    for file in ${check_files[*]}
    do
        check_cmd="python2 $cpplint_path --linelength=80"
        echo -e "33[33m =========== check file $file =============33[0m"
        check_cmd="$check_cmd"$file
        eval $check_cmd
        echo -e "33[45m ==========================================33[0m"
    done
fi

 运行:

cpplint_dir$sudo bash cpplint_shell.sh

这个脚本是直接在terminal终端打印信息,更进一步,其实可以尝试生成检测报告,也可以尝试将检测信息当成注释放在源文件。

注意,一定要使用bash,被这个问题搞了半天,(# ̄~ ̄#)

这是因为sh和bash的shell解析器版本不一样,版本不同,解析规则有不一样的地方。

使用sh运行的时候出现bad substitution的错误,使用bash就没有问题啦。。。

2. windows系统使用过程

2.1 安装python,注意设置系统环境变量,将python的安装目录写入path环境变量,保存cpplint.py文件;

2.2 运行命令或者脚本文件;

命令行:

cpplint_py_dir$python cpplint.py test.cpp

batch文件:

echo off
python cpplint.py test.cc --output=vs7 > report.txt 2>&1
pause

执行bat文件即可;

2.3 批量检测分析;

步骤:在目录下创建src和reports目录;将要检测的源文件置于src目录;修改batch文件并执行;

echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set suffix=.report.txt
set src_path=src
set reports_path=reports
for %%i in (%src_path%/*.cpp) do (
echo %%i
set report_name=%reports_path%/%%i%suffix%
set src_name=%src_path%/%%i
echo src_name=!src_name!
echo report_name=!report_name!
python cpplint.py !src_name! --counting=toplevel --output=vs7 > !report_name! 2>&1
)
pause

注意,1)等号=两边没有空格等。2)必须在dos下实验目录运行bat文件。3)bat文件是dos下的批处理文件。

运行脚本:

cpplint_py_dir$./cpplint_batch.bat

参考

1. 静态代码分析工具汇总;

2. Google 开源项目风格指南 (中文版);

3. google code style on github;

4. Google代码规范工具Cpplint的使用_fengbingchun_windows;

5. cpplint_github;

6. cpplint使用技巧;

7. windows_batch_process;

8. cpplint_comment_error;

原文地址:https://www.cnblogs.com/happyamyhope/p/11301527.html