1. 程式人生 > >讓Visual Studio的程式碼分析工具提高你的程式碼質量

讓Visual Studio的程式碼分析工具提高你的程式碼質量

靜態程式碼分析工具,第三方的有很多。其實visual studio有的版本里面也有的哦,通過Q—A的引子希望本文可以起到拋磚引玉的作用。

Q:為什麼我的Visual Studio中沒有程式碼分析功能([分析]選單中[僅對...執行程式碼分析])。

A:你的vs版本是下面其中之一嗎?
   Microsoft Visual Studio 2005 Team Edition for Software Developers
   Visual Studio Team System Development Edition 或 Visual Studio Team Suite
   Visual Studio 2010 Premium 或 Visual Studio 2010 Team Suite
   Visual Studio 2012 Premium 或 Visual Studio 2012 Ultimate 


Q:程式碼分析得出的都是些什麼樣的結果?
A:[專案]選單--》[屬性]--》[配置屬性]--》[程式碼分析]--》[託管程式碼分析規則]裡有詳細的規則,下面是幾個例子。
   warning C6326: Potential comparison of a constant with another constant
   warning C6202: Buffer overrun for '...', which is possibly stack allocated, in call to 'memset': length 'xxx' exceeds buffer size 'yyy'
   warning C6386: Buffer overrun: accessing 'argument 1', the writable size is 'xxxx' bytes, but 'yyy' bytes might be written: Lines: ... ... ...
   warning C6385: Invalid data: accessing 'argument 2', the readable size is 'xxx' bytes, but 'yyy' bytes might be read: Lines: ... ... ... 


Q:分析得出的這些警告後,我們要做什麼?
A:一句話,找到根本原因,修改使之更安全;更進一步,努力寫出不被程式碼分析工具警告的程式碼。
   之所以重要,是因為這些警告很可能會導致Release版本出類似buffer overrun之類難搞的問題,而且這些問題多數在debug下並不再現。


Q:msdn官方連結
A:http://msdn.microsoft.com/zh-cn/library/4dtdybt8(v=vs.90).aspx
   連結的標題即為“編寫高質量的程式碼”,有下面這樣一段話。
   {從一開始就確保質量。質量不是您可以在以後容易地增添的元素。過於複雜、過於隱蔽或在產品生命週期中發現過遲的問題通常得不到修復。}
   {Ensure quality from the start. Quality is not something that can be easily added later. Problems that are too complex, too obscure, or are discovered too late in the product cycle are usually not fixed.}