Wednesday, October 19, 2011

using scan-build from clang with cmake

If you've wanted to add static analysis to your C/C++ project which uses CMake but didn't know how, then you'll want to read this.  This post is mostly a note for myself so I don't have to google it later ;)

If you're using Debian it's actually quite easy.  Just install the clang package with:
# apt-get install clang
After that's done installing, change directories into your source directory.  Now typically I use a separate build directory since it helps keep my source clean and allows me to do a build with gcc and clang from the same source directory.

Anyways, since we want to do an analysis with clang's scan-build, we're going to create a new build directory in our top level source directory.  For example:
$ mkdir build-analyze
The next commands will be need to be run from this new directory, so change into it now.
 $ cd build-analyze
 Now we need to generate our build system with cmake and compile it, but we need to point cmake to clang's ccc-analyzer.  In Debian, this program is located in /usr/share/clang/scan-build/ccc-analyzer.

$ cmake -DCMAKE_C_COMPILER=/usr/share/clang/scan-build/ccc-analyzer ..
$ scan-build make
When you're build is finished you will see two lines, like the ones shown below.
scan-build: 6 bugs found.
scan-build: Run 'scan-view /tmp/scan-build-2011-10-19-1' to examine bug reports.
As you can see, it found 6 bugs in my code.  To view the bugs, the easiest way is to run:
$ scan-view /tmp/scan-build-2011-10-19-1
This will start up a local web server, and open it in your default web browser.  From here you can review the bugs and determine how to fix them!

Hope this was helpful!

3 comments:

  1. You may also need to set the following environment variables:

    export CCC_CC=clang
    export CCC_CXX=clang++

    Otherwise it will default to gcc as the compiler.

    ReplyDelete
  2. how does this command work:
    "scan-view /tmp/scan-build-2011-10-19-1"
    these folder/files are not available in directory

    ReplyDelete
    Replies
    1. The directory to pass to scan-view will be displayed as one of the last lines of the scan-build output.

      Delete