Install LLVM/Clang (Optional)
This tutorial is to show how to use the clang static analyzer tool to automatically find bugs in your objective-c code. I am going to show you the long but probably better off way by first installing llvm and clang then installing the tool. Lets get started.
First thing first, go to http://clang.llvm.org/get_started.html and read up if you wish. Otherwise here we go. Open a terminal and svn a current version of llvm down:
svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm
Next lets configure and make llvm:
cd llvm ./configure; make
This will take a minute to build. After it’s completed lets get clang:
cd tools svn co http://llvm.org/svn/llvm-project/cfe/trunk clang
After this has been downloaded we need to build this as well:
cd clang make
From here I like to install llvm and clang into the command line:
cd .. cd .. sudo make install
Now llvm libraries are installed. We need to install clang now:
cd tools cd clang sudo make install
Clang should be installed now, so lets test it. Quit the terminal and open a new one and try this:
clang --helpIf everything worked you get something like this:
Install the Clang Analyzer Tool
Yes, we didn’t actually need these things installed to use the static tool but it’s nice to have. So now for the static analyzer tool. You can find a download link here: http://clang.llvm.org/StaticAnalysis.html. After you’ve downloaded the zip unzip it. Find a place to put these files. I personally like it in the /usr/bin but it’s up to you. Since, I’m doing the demo I will use that. So first lets create a directory there:
cd /usr/bin sudo mkdir objc-analyzer
Then just drag the files from the zipped folder in there. So it should something like this:
Almost done, we need to set the bash path to look here. Simply open the bash profile and export the new path like such:
sudo nano /etc/profile
And add this to the bottom:
PATH=$PATH:/usr/bin/objc-analyzer/ export PATH
Save it and quit the terminal and open a new one. The analyzer should be working now. Test it by typing:
scan-build
If everything worked as planned you get some output:
Run the Clang Analyzer Tool
Now we are ready to move on to the fun easy stuff. Find an old project with a lot of bugs and go there in the terminal, clean the project first (yes you need to do this every time), and run scan build. It was recommended to always use it on the “Debug” configuration.
cd /workspace/EyeConsoleCD scan-build xcodebuild -configuration Debug clean scan-build -V xcodebuild -configuration Debug
This should run and open the report if any bugs were found (-V automatically opens scan-view which opens the report). Here is what it found in my project:
Whoa lets take a look at that leak:
No way a real bug
Anyway, hope that helped and thanks for reading. Here’s the picture tutorial if you don’t like reading.