Search code examples
c++cmakecppcheck

Cppcheck Cmake integration: abort build on warning


I just started using cppcheck in a C++ project and learned that it can be integrated into cmake. In my cmake project, I integrated it into the CMakeLists.txt file via

find_program(CMAKE_CXX_CPPCHECK NAMES cppcheck)
if(NOT CMAKE_CXX_CPPCHECK)
  message(FATAL_ERROR "Could not find the program cppcheck.")
endif()
list(APPEND CMAKE_CXX_CPPCHECK "--enable=all" )

Now, during the compilation process, cppcheck runs fine. I have set -WError for all my compiler warnings, is there a way to do the same for cppcheck, i.e. make the build fail in case a cppcheck warning is thrown?


Solution

  • When a make program calls programs like the compiler, linker or whatever other tool like cppcheck in your case, then the return value of the program is evaluated. If any program returns the value 0, then this is considered as successful by make so that it continues. If any program returns another value then 0, then make fails and does not continue. That is a well-known convention. So all you have to do is to configure cppcheck in a way that it returns 0 in case of success and another value in case of failure. You can achieve that with the parameter --error-exitcode=1:

    list(APPEND CMAKE_CXX_CPPCHECK "--enable=all" "--error-exitcode=10")
    

    From cppcheck documentation:

    --error-exitcode=<n> If errors are found, integer [n] is returned instead of
                         the default '0'. '1' is returned
                         if arguments are not valid or if no input files are
                         provided. Note that your operating system can modify
                         this value, e.g. '256' can become '0'.
    

    However, this will also fail, if there is any message of cppcheck. You probably need to adjust the enable switch to severity classes which are of interest for you. Alternatively, you can suppress messages, please see cppcheck command line documentation how to achieve that.