Skip to content

Instantly share code, notes, and snippets.

@bjornblissing
Last active August 31, 2023 23:18
Show Gist options
  • Save bjornblissing/60c2d425532e6dd534841a8d1d2ffe76 to your computer and use it in GitHub Desktop.
Save bjornblissing/60c2d425532e6dd534841a8d1d2ffe76 to your computer and use it in GitHub Desktop.
How to run CppCheck inside Visual Studio as a CMake custom build target.
cmake_minimum_required(VERSION 3.10)
project(MyExampleProject VERSION 1.0 LANGUAGES CXX)
add_executable(my_project main.cpp)
# Add Analyze with CppCheck target if CppCheck is installed
if(WIN32)
# Find CppCheck executable
find_program(CMAKE_CXX_CPPCHECK cppcheck NAMES cppcheck HINTS $ENV{PROGRAMFILES}/cppcheck)
# If CppCheck executable found
if(CMAKE_CXX_CPPCHECK)
# Check CppCheck version
set(CPP_CHECK_CMD ${CMAKE_CXX_CPPCHECK} --version)
execute_process(COMMAND ${CPP_CHECK_CMD}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
RESULT_VARIABLE CPP_CHECK_RESULT
OUTPUT_VARIABLE CPP_CHECK_VERSION
ERROR_VARIABLE CPP_CHECK_ERROR)
# Check if version could be extracted
if(CPP_CHECK_RESULT EQUAL 0)
# Get number of CPU cores
include(ProcessorCount)
ProcessorCount(CPU_CORES)
# Append desired arguments to CppCheck
list(
APPEND CMAKE_CXX_CPPCHECK
# Using the below template will allow jumping to any found error from inside Visual Studio output window by double click
"--template \"${CMAKE_SOURCE_DIR}/{file}({line}): {severity} ({id}): {message}\""
# Use all the available CPU cores
"-j ${CPU_CORES}"
# Only show found errors
"--quiet"
# Desired warning level in CppCheck
"--enable=style"
# Optional: Specified C++ version
"--std=c++17"
# Optional: Specified platform
"--platform=win64"
# Optional: suppression file stored in same directory as the top level CMake script
"--suppressions-list=${CMAKE_SOURCE_DIR}/cppcheck_suppressions.txt"
# Optional: Use inline suppressions
"--inline-suppr"
# Run CppCheck from the working directory, as specified in the add_custom_target command below
"."
)
add_custom_target(ANALYZE_CPPCHECK DEPENDS my_project
COMMAND ${CMAKE_CXX_CPPCHECK}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMENT "Static code analysis using ${CPP_CHECK_VERSION}"
)
endif()
endif()
endif()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment