detect-coverage.cmake 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # detect-coverage.cmake -- Detect supported compiler coverage flags
  2. # Licensed under the Zlib license, see LICENSE.md for details
  3. macro(add_code_coverage)
  4. # Check for -coverage flag support for Clang/GCC
  5. if(CMAKE_VERSION VERSION_LESS 3.14)
  6. set(CMAKE_REQUIRED_LIBRARIES -lgcov)
  7. else()
  8. set(CMAKE_REQUIRED_LINK_OPTIONS -coverage)
  9. endif()
  10. check_c_compiler_flag(-coverage HAVE_COVERAGE)
  11. set(CMAKE_REQUIRED_LIBRARIES)
  12. set(CMAKE_REQUIRED_LINK_OPTIONS)
  13. if(HAVE_COVERAGE)
  14. add_compile_options(-coverage)
  15. add_link_options(-coverage)
  16. message(STATUS "Code coverage enabled using: -coverage")
  17. else()
  18. # Some versions of GCC don't support -coverage shorthand
  19. if(CMAKE_VERSION VERSION_LESS 3.14)
  20. set(CMAKE_REQUIRED_LIBRARIES -lgcov)
  21. else()
  22. set(CMAKE_REQUIRED_LINK_OPTIONS -lgcov -fprofile-arcs)
  23. endif()
  24. check_c_compiler_flag("-ftest-coverage -fprofile-arcs -fprofile-values" HAVE_TEST_COVERAGE)
  25. set(CMAKE_REQUIRED_LIBRARIES)
  26. set(CMAKE_REQUIRED_LINK_OPTIONS)
  27. if(HAVE_TEST_COVERAGE)
  28. add_compile_options(-ftest-coverage -fprofile-arcs -fprofile-values)
  29. add_link_options(-lgcov -fprofile-arcs)
  30. message(STATUS "Code coverage enabled using: -ftest-coverage")
  31. else()
  32. message(WARNING "Compiler does not support code coverage")
  33. set(WITH_CODE_COVERAGE OFF)
  34. endif()
  35. endif()
  36. # Set optimization level to zero for code coverage builds
  37. if (WITH_CODE_COVERAGE)
  38. # Use CMake compiler flag variables due to add_compile_options failure on Windows GCC
  39. set(CMAKE_C_FLAGS "-O0 ${CMAKE_C_FLAGS}")
  40. set(CMAKE_CXX_FLAGS "-O0 ${CMAKE_CXX_FLAGS}")
  41. endif()
  42. endmacro()