Matt Rajca

Aug 14 2011

LLVM, Code Coverage, and Xcode 4

The ability to generate code coverage reports has been one of the notable features missing from the LLVM/Clang compiler. As of June 8, 2011, the Clang frontend can finally generate code coverage reports using the same flags that were supported by GCC. At the time of this writing, these flags haven’t made their way into Xcode’s build settings UI. I have no doubt they will be integrated into a future release of Xcode, but until that happens, we can always compile our own build of Clang and manually pass in the compiler flags necessary to generate code coverage reports.

Below are the steps required to check out, compile, and install the tip-of-tree build of LLVM/Clang.

# check out the source to LLVM
svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm

# check out the source to Clang
cd llvm/tools
svn co http://llvm.org/svn/llvm-project/cfe/trunk clang

# configure the project for compilation
cd..
./configure --prefix=/opt --enable-optimized
make -j8           # build with 8 threads
sudo make install  # install to /opt

If all goes well, a new binary of the Clang compiler should now reside in /opt/bin/. Next, we need to tell Xcode to use our newly-built compiler instead of the build it ships with. This should be done for each target you want to generate code coverage reports, or at the project level. In Xcode, open the Build Settings pane of the desired target and choose ‘Add Build Setting’ from the bottom toolbar; select ‘Add User-Defined Setting’ from the pop-up menu that appears. Enter CC for the setting name and /opt/bin/clang as its value. Xcode will now build the target using our custom-built compiler.

Xcode 4 CC Setting

While we’re in the Build Settings pane, find the Other C Flags setting and add -fprofile-arcs and -ftest-coverage on to the list. These flags will tell Clang to generate gcov files for each class in our target.

Lastly, we have to link against libprofile_rt.a (instead of libgcov.a, which was required by GCC). In Xcode 4, switch to your target’s Build Phases pane and expand the ‘Link Binary With Libraries’ section. Click on the ‘Plus’ button, choose ‘Add Other’, and navigate to /opt/lib. Select libprofile_rt.dylib from the list of files.

And that’s it! If you build and run your target, Xcode will now output gcda and gcov files to a well-hidden path inside the DerivedData directory. To find it, right click on your target in Xcode’s Products group, and select ‘Show in Finder’. Navigate up the path hierarchy to the Build folder, as shown below.

Target Build Folder

Finally, open up the Intermediates/$TARGET.build/$CONFIG/$TARGET.build/Objects-normal/$ARCH subfolder. Inside, you’ll find the aforementioned gcda and gcov files. Since Clang outputs these files in the same format as GCC, they are compatible with tools such as CoverStory.

33 notes

  1. do-nothing reblogged this from mattrajca
  2. mattrajca posted this
Page 1 of 1