CMake CppCheck static code checks
CMake has built-in support for C/C++ static code analysis tools such as CppCheck. Apply CppCheck to CMake targets with CMakeLists.txt by setting CMAKE_CXX_CPPCHECK.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required(VERSION 3.19) | |
project(DemoCppCheck LANGUAGES C CXX) | |
option(cppcheck "Run CppCheck static code analysis") | |
if(cppcheck) | |
find_program(cppcheck_exe NAMES cppcheck REQUIRED) | |
set(cppcheck_opts --enable=all --inline-suppr --quiet --suppressions-list=${PROJECT_SOURCE_DIR}/cppcheck.supp) | |
set(CMAKE_C_CPPCHECK ${cppcheck_exe} --std=c11 ${cppcheck_opts}) | |
set(CMAKE_CXX_CPPCHECK ${cppcheck_exe} --std=c++20 ${cppcheck_opts}) | |
endif() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
missingIncludeSystem | |
constParameter | |
unusedFunction | |
unmatchedSuppression |
File “cppcheck.supp” contains suppressions for false positives.
NOTE: CMake runs cppcheck from an arbitrary directory, so per-file suppressions in the file don’t work as usual.
To suppress a warning for a specific file, use the --suppress
option to cppcheck in CMakeLists.txt like:
set_property(TARGET MyTarget PROPERTY CXX_CPPCHECK "${CMAKE_CXX_CPPCHECK};--suppress=containerOutOfBounds")
Don’t just blindly modify code based on CppCheck output. Think of it like any code analysis tool–there are false positives (and false negatives).