Using Cppcheck To Produce Better Code (转)
Cppcheck is an open source static code analyzer tool for C/++. With its default arguments, it produces quite a low rate of false positives and identifies numerous areas in which bugs can be fixed, scope reduced, performance enhanced, and so forth.
Basic Usage
Cppcheck, in its basest form, simply needs to be run as:
./cppcheck path_to_check |
Tips / Suggested Usage
In its basest form, cppcheck will not do a lot of things you'll want it to do and will do some things you don't want it to do. A more appropriate commandline looks like:
./cppcheck --force --inline-suppr --template '{file}:{line},{severity},{id},{message}' -i "$EXTRA_INCLUDE_PATHS" -q $( for b in $( for a in $(find "$CODE_PATH" | egrep '\.h$' ); do dirname $a; dirname $(dirname $a); done | sort -u); do echo -n " -I $b" ; done) "$CODE_PATH" >err.txt 2 > err2.txt; more err2.txt
|
We will look at each of those arguments in a little more detail:
* --force: Without --force, cppcheck will give up whenever the code gets too complicated. Which, at least in ITK, is "usually".
* --inline-suppr: This tells cppcheck to enable "suppressions". Suppressions are comments of the form "// cppcheck-suppress ErrorType", which says that if cppcheck finds an error of that type on the next line, ignore it. This is a way to suppress false positives.
* --template: This tells cppcheck to use a different format for outputting its errors. The main addition is the inclusion of id, which lets us see what the error type is so that we can suppress if necessary.
* -i: Allows the user to specify extra include paths. Without it, cppcheck may not be able to find out where everything is in order to look for errors.
* -q: Means "quiet", which eliminates a lot of spam and makes sifting through the output a lot easier.
* The nested for loops are way to make sure that all include files are examined by cppcheck. You can try omitting it, but you may need it in some cases.
* The redirection at the end saves the output. All errors will be in err2.txt (stderr)
It is also possible to turn on additional checks, but I do not recommend them. The overwhelming majority of them were false positives.
Sifting Through Your Results
In theory, you can just go through the results of err2.txt; however, in practice, you may want to cat err2.txt and grep out (grep -v) "errors" that you discover aren't really errors. For example, grep -v ThirdParty was useful in examining ITK.
Cautions
Note that some things cppcheck reports may not be false positives if your application is standalone, but if things build against your application, the recommended changes may cause problems. A notable example from ITK was when it recommended, for performance, changing some functions to pass-by-reference. This is generally a good idea, but could break legacy code.
上一篇: php过滤敏感词实例代码
下一篇: 第 2-6 课:生命周期及按键监听