Wednesday, 6 February 2013

Clang Static Analysis

Producing quality software is, or should be, the goal of any programmer.  Whether you're sat in your bedroom boshing out code left and right to get your smart idea off the ground, or whether you're sat where I am right now, in the offices of an digital advertising agency trying to get the most and best out of the guys sat next to me.

One good way of checking that the code you've written isn't full of unintended side effects is to run the static analyser ( over it.  You can do this in XCode by using cmd+shift+B to build your project.  It will report any "infringements" that it feels you have made.  It is not flawless and may report false positives (here's a bit on that:  You can also change your target settings to run the analyser automatically on build (the build option is "Run Static Analyzer").

The static analyser will run if you build your project from the command line using xcodebuild (and there's an option RUN_CLANG_STATIC_ANALYZER that can be set to YES if you want).  The warning appears within the compilation output seemingly cannot be converted to an error (even if you set "Treat Warnings as Errors" in your target settings).

There is a tool called scan-build that's part of LLVM that does the same thing but also produces readable HTML output.

The --status-bugs flag ensures that you get a non-0 exit code if any problems are found by the static analyzer (and the command echo $? prints out the exit code from the last command entered).

There's a Jenkins plugin ( you can use where it'll fail the build if a certain number of problems are found.  However, I've never used this plugin and it hasn't been updated since April 2012 (which may or may not mean anything).

The LLVM project version of the static analyzer is the bleeding-edge, both in terms of development builds (you can get the tip of the tree) and stable builds.  Apple doesn't always update XCode when a new version of LLVM or the static analyser are released.