Monday, October 8, 2012

Poor Man’s Visual Studio Cppcheck Integration

Cppcheck is a good tool to have in your arsenal.  Anything that helps me avoid stupid mistakes is very welcome.  The problem is that if you use Visual Studio, you either have to use the separate Cppcheck GUI or pay an arm and a leg for something like Visual Lint.  If you want a more convenient way to run Cppcheck on your code, but don't want to shell out $200 for the privilege, there's a fairly easy way to do a simple integration.

Getting Started

First things first, download the latest version Cppcheck from and install it.  This will give you both the command line version and the GUI version of Cppcheck.

Create a Visual Studio External Tool

  • In Visual Studio, open menu Tools→External Tools...
  • click the Add button
  • set the Title, for example Cppcheck
  • set Command to C:\Program Files (x86)\Cppcheck\cppcheck.exe
  • set Arguments to --quiet --verbose --template=vs $(ItemPath)
  • set Initial Directory to $(ItemDir)
  • make sure Use Output window checkbox is enabled
  • click on the Move Up button repeatedly until your entry is at the top of the list, this will make it easier to identify you new command as you can count on it being called Tools.ExternalCommand1
  • click OK.
Voila! You now have a Cppcheck entry in your Tools menu:

Use the Tool

You can now use select the Cppcheck menu entry any time you want to run Cppcheck on a file. The cool thing about the --template=vsswitch is that you can click on a Cppcheck error and Visual Studio will automatically take you to that line of code:

Automate Cppcheck to Run on File Save

Now that we have created a command to run Cppcheck, we can have it run automatically after a file save:
  • go to menu ToolsMacrosMacros IDE, this will bring up a the Macros IDE
  • on the left hand side there should be a Project Explorer panel
  • in the Project Explorer panel, double click on EnvironmentEvents module
  • Insert the following code in the module:
Private Sub DocumentEvents_DocumentSaved( ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentSaved
    If Document.Language = "C/C++" Then
    End If
End Sub
  • now save the module, close the Macros IDE, and you're good to go

No comments:

Post a Comment