代碼風格審查工具Cpplint

1,簡介

Cpplint是一個Python腳本,作爲一款開源免費的代碼靜態檢測工具,Google也使用它作爲自己的C++代碼檢測工具,也就是說,只要你想代碼遵從Google C++代碼規範,那麼Cpplint將會提供很好的代碼靜態檢測支持。

  • Cpplint.py支持的文件格式包括.cc、.h、.cpp、.cu、.cuh。
  • Cpplint只是一個代碼風格檢測工具,其並不對代碼邏輯、語法錯誤等進行檢查。

2,安裝

使用python安裝cpplint模塊

pip install cpplint 

最新版本v1.4.5 支持python2和python3版本。

3,命令行的詳細使用

寫一個測試文件test.cpp,內容如下:

#include <iostream>
 
using namespace std;
 
int main()
{
	cout<<"hello !"<<endl;
	
	return 0;
}

運行代碼檢查

cpplint.exe .\test.cc

會發現有以下錯誤:

常見報錯原因

No copyright message found 沒有寫Copyright引用
Tab found; better to use spaces 沒有使用四個空格代替縮進
Lines should be <= 80 characters long 存在大於80字符的行
Should have a space between // and comment 應該在//和註釋之間有一個空格
An else should appear on the same line as the preceding } 符號“{”要代碼同一行
If an else has a brace on one side, it should have it on both [readability/braces] 上兩個錯誤經常一起出現,爲大括號的位置不合規範
Extra space for operator ++ ++符號和變量間不能有空格
Redundant blank line at the end of a code block should be deleted 代碼塊最後的空行應該被刪除
Line contains invalid UTF-8 (or Unicode replacement character) 使用了中文註釋報的錯
Line ends in whitespace 代碼行最後存在空格
   

按照錯誤提示,對test.cpp文件進行修改,內容如下:

/*
# Copyright (c) 2015 Bingchun Feng. All rights reserved.
*/

#include <iostream>

int main() {
  std::cout << "hello !" << std::endl;
  return 0;
}

 執行,如下,發現所有錯誤全部清理掉了:

4,參考鏈接

  1. 谷歌編碼風格
  2. Google C++ Style Guide
  3. Cpplint

 

 

 

 

發佈了18 篇原創文章 · 獲贊 18 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章