Specify ruleset for Visual Studio code analysis on command line or from CMake

I am not sure how far this works for VS2013 solutions. With Visual Studio 2015 I am using Project User Templates (*.vcxproj.user) with something along the following lines:

C:\MyProject\Template.USERNAME.user

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <CodeAnalysisRuleSet>@CMAKE_SOURCE_DIR@\SecurityRecommended.ruleset</CodeAnalysisRuleSet>
    <RunCodeAnalysis>true</RunCodeAnalysis>
  </PropertyGroup>
</Project>

You will probably have to change a few things like the ToolsVersion to 12.x.

The @CMAKE_SOURCE_DIR@ will automatically get replaced by cmake when you use the CONFIGURE_FILE function to generate the actual PROJECT.vcxproj.user file. I have the following line in the CMakeLists.txt of my projects:

SET(USER_NAME $ENV{USERNAME} CACHE STRING UserName)
SET(USER_FILE ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.vcxproj.user)
CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/Template.${USER_NAME}.user ${USER_FILE} @ONLY)

In the end, I would assume you could user-define anything that's in the PROJECT.vcxproj with those templates.


If you are trying to solve this for a command line build--either via cmake --build or direct invocation of msbuild--and not when using the generated solution with Visual Studio, you can set the relevant properties when you invoke the build.

With cmake driving the build:

PS c:\build-dir> cmake --build . -- '/p:RunCodeAnalysis=true' `
                     '/p:CodeAnalysisRuleSet=NativeRecommendedRules.ruleset'

With MSBuild driving the build:

PS c:\build-dir> msbuild ALL_BUILD.vcxproj '/p:RunCodeAnalysis=true' `
                     '/p:CodeAnalysisRuleSet=NativeRecommendedRules'

If you have a custom ruleset in a custom directory, you will also need to set the property CodeAnalysisRuleSetDirectories:

PS c:\build-dir> cmake --build . -- '/p:RunCodeAnalysis=true' `
                     '/p:CodeAnalysisRuleSet=custom.ruleset' `
                     '/p:CodeAnalysisRuleSetDirectories=c:\src\ruletsets'

(Tested with CMake 3.8.0, MSBuild 15.3.409.57025, and Visual C++ 2017 19.11.25506.)