option(CPPCHECK "Turns cppcheck processing on if executable is found." OFF)

find_program(CPPCHECK_PATH NAMES cppcheck)

# export compile commands to json file to be used by cppcheck
set(CMAKE_EXPORT_COMPILE_COMMANDS 1)
set(CPPCHECK_COMPILE_COMMANDS "${CMAKE_BINARY_DIR}/compile_commands.json")

# output directory for codecheck analysis
set(CPPCHECK_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/cppcheck_results)

if(CPPCHECK AND CPPCHECK_PATH AND NOT CPPCHECK_ADDED)

  set(CPPCHECK_ADDED ON)

  if (NOT TARGET cppcheck)

  add_custom_target(cppcheck
                    COMMAND rm -rf ${CPPCHECK_OUTPUT_DIRECTORY}\;
                            mkdir -p ${CPPCHECK_OUTPUT_DIRECTORY}\;
                            ${CPPCHECK_PATH}
                            --project=${CPPCHECK_COMPILE_COMMANDS}
                            --plist-output=${CPPCHECK_OUTPUT_DIRECTORY}
                            --enable=all
                            --inline-suppr
                    )
  endif()
endif()
