所謂靜態代碼檢查就是使用一個工具檢查我們寫的代碼是否安全和健壯,是否有隱藏的問題。
比如無意間寫了這樣的代碼:
- <span style="font-size: 14px;">int n = 10;
- char* buffer = newchar[n];
- buffer[n] = 0;</span>
int n = 10;
char* buffer = new char[n];
buffer[n] = 0;
這完全是符合語法規范的,但是靜態代碼檢查工具會提示此處會溢出。也就是說,它是一個更加嚴格的編譯器。
使用比較廣泛的靜態代碼檢查工具有cppcheck pc-lint等。
pc-lint是資格最老,最強力的代碼檢查工具,但是是收費軟件,並且配置起來有一點點麻煩。
cppcheck是免費的開源軟件。使用起來也很方便。
從 http://cppcheck.sourceforge.net/ 下載最新的cppcheck。
安裝完就可以使用里面的cppcheck-gui來檢測代碼。
參考這里(http://avitebskiy.blogspot.tw/2012/10/poor-mans-visual-studio-cppcheck.html),可以方便的把cppcheck嵌入到vs,然后可以方便的對一個文件進行檢查,而且支持錯誤跳轉。
- click the Add button
- set the Title, for example Cppcheck
- set Command to C:\Program Files (x86)\Cppcheck\cppcheck.exe
- set Arguments to --quiet --verbose --template=vs $(ItemPath)
- set Initial Directory to $(ItemDir)
- make sure Use Output window checkbox is enabled
- click on the Move Up button repeatedly until your entry is at the top of the list, this will make it easier to identify you new command as you can count on it being called Tools.ExternalCommand1
- click OK.