Erik's Thoughts and Musings

Apple, DevOps, Technology, and Reviews

Using the Clang Static Analyzer

One of the tools I learned about at both WWDC and in my CS193P class is Clang.

Clang is a front-end processor for a compiler. It analyzes your code and is pretty effective at finding not only compilation warnings and errors, but also difficult to find logic errors like memory leaks in your C or Objective-C code (no C++ support yet).

Since the installation and usage instructions are a little lacking, here are the steps to get it working on one of your projects:

  • Download the Mac version of Clang here.
  • Expand the tarball using StuffIt or one of the built in OS decompression tools. A folder should be created something like "checker-0.211"
  • Open the Terminal.
  • If you are using Bash, edit your .bashrc or .bash_profile in your home directory and add the "checker-0.211" folder to your path. Something like this:
    PATH=$PATH:~/Downloads/checker-0.211

  • Open one of your Cocoa projects in Xcode that has Objective-C or C.
  • THIS IS IMPORTANT: Do a Clean Build.
  • Go back to the Terminal.
  • Change directory to your project folder for the Cocoa project.
  • If you are running it against a Mac application, run the following command:
    scan-build -k -V xcodebuild -configuration Debug

  • If you are running it against an iPhone application, run the following command:
    scan-build -k -V xcodebuild -configuration Debug -sdk iphonesimulator3.0

  • A full compile will happen with some extra analyze steps. C++ or Objective-C++ files are not analyzed but still compiled.
  • When the build is done, a mini-webserver is kicked off and you get a report. Within the report is a number of line items about potential issues. NOTE: There could be false positives.
  • Clicking on one of the items gives you an HTML view of not only the code in the module, but in-screen warnings, like so:

  • It contains really neat information that could save a user a bunch of time using a tool like Instruments. The best part is that Clang is open source, so ports to other platforms already exist. I can't wait until the C++ processing is working!