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