if(QT_PROTOBUF_MAKE_COVERAGE AND UNIX)
    message(STATUS "Enable gcov")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")
    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --coverage")
    add_custom_target(coverage)
endif()

function(add_coverage_target)
    set(options)
    set(oneValueArgs TARGET)
    set(multiValueArgs)
    cmake_parse_arguments(add_coverage_target "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
    set(GCOV_OUTPUT_DIR ${QT_PROTOBUF_BINARY_DIR}/gcov/${add_coverage_target_TARGET})
    set(OBJECTS_DIR ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${add_coverage_target_TARGET}.dir)
    set(COVERAGE_TARGET ${add_coverage_target_TARGET}_coverage)
    if(QT_PROTOBUF_MAKE_COVERAGE AND UNIX)
        find_program(GCOV_EXECUTABLE "gcov")
        if(GCOV_EXECUTABLE STREQUAL GCOV_EXECUTABLE-NOTFOUND)
            message(FATAL_ERROR "Coverage enabled for target ${add_coverage_target_TARGET}, but gcov is not installed")
        endif()
        file(MAKE_DIRECTORY ${GCOV_OUTPUT_DIR})
        add_custom_target(${COVERAGE_TARGET} DEPENDS ${add_coverage_target_TARGET})
        add_custom_command(TARGET ${COVERAGE_TARGET} COMMAND ${GCOV_EXECUTABLE} ${OBJECTS_DIR}/*.o -b -c
            WORKING_DIRECTORY ${GCOV_OUTPUT_DIR})


        find_program(GCOVR_EXECUTABLE "gcovr")
        if(NOT GCOVR_EXECUTABLE STREQUAL GCOVR_EXECUTABLE-NOTFOUND)
            set(GCOVR_OUTPUT_DIR ${GCOV_OUTPUT_DIR}/html)
            file(MAKE_DIRECTORY ${GCOVR_OUTPUT_DIR})
            add_custom_command(TARGET ${COVERAGE_TARGET} COMMAND ${GCOVR_EXECUTABLE} -g -k -r
                ${CMAKE_SOURCE_DIR} --html --html-details -o ${GCOVR_OUTPUT_DIR}/${add_coverage_target_TARGET}.html ${OBJECTS_DIR} .
                WORKING_DIRECTORY ${GCOV_OUTPUT_DIR})
        endif()
        add_dependencies(coverage ${COVERAGE_TARGET})
    endif()
endfunction(add_coverage_target)
