标签搜索

目 录CONTENT

文章目录
C++

c++代码风格检查:cpplint的使用与改造

陈铭
2021-07-28 / 0 评论 / 0 点赞 / 683 阅读 / 583 字 / 正在检测是否收录...

安装cpplint

cpplint是个pypi模块,需要python支持,使用pip安装pip install cpplint

它遵循的代码风格规范为Google C++ Style,英文页面。这里还有个中文的翻译页面

使用cpplint检查风格

如果是linux下使用pip安装后是找不到cpplint命令的,find / -name cpplint并且ln -s <location> /usr/bin/cpplint

window可以直接执行,因为window安装时候把pypi模块的可执行文件路径加进了环境变量了。如图所示:
image

安装完执行

默认检查

cpplint [OPTIONS] <filename>

递归检查

cpplint --recursive <path>

输出到文件

cpplint默认的标准错误输出流,要重定向到文件
cpplint --output=junit <path> 2>xxx.xml

如何改造?

我们可以从github上拉取源码,修改源码里面的cpplint.py文件。该文件就是所有正则匹配规则书写的地方

就比如cpplint规定,函数体的左花括号{是要在同一行的行末尾,而公司的规范是左花括号必须单独另起一行。

# cpplint的规范
int fun(int a){
	...
}

# 公司的规范
int fun(int a)
{
	...
}

所以我就在对应位置改造了它的匹配规则

# 左花括号的检测是在CheckBraces函数里面
def CheckBraces(filename, clean_lines, linenum, error):
  """Looks for misplaced braces (e.g. at the end of line).

  Args:
    filename: The name of the current file.
    clean_lines: A CleansedLines instance containing the file.
    linenum: The number of the line to check.
    error: The function to call with any errors found.
  """

  line = clean_lines.elided[linenum]        # get rid of comments and strings

  # 检测左花括号的逻辑:Search函数是检测存在,Match函数是检测完全匹配
	if Search(r'\)\s*\{\s*$', line): # 存在“) {”结尾的字符串
    prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
    if (not line == "{" and
		# 并不属于if、for、while、switch的语句
		not Search(r'\b(if\s*\(|for\s*\(|while\s*\(|switch\s*\()\s*', line) and
		# 并不存在&&和||
		not Search(r'(&&|\|\|)\s*', line) and
		# 当前行的字符数没有超标
        not (GetLineWidth(line) > _line_length - 2 and '[]' in line)):
      error(filename, linenum, 'whitespace/braces', 4,
            '{ should almost always start a new line alone without the beginning of space for function')

谷歌的其他代码风格规范

当然,google还有很多语言的风格规范,都在github

0

评论区