Additional CMake functionality. Most of the modules are from Ryan Pavlik

Overview

Additional CMake Modules

Introduction

This is a collection of additional CMake modules. Most of them are from Ryan Pavlik (http://academic.cleardefinition.com).

How to Integrate

These modules are probably best placed wholesale into a "cmake" subdirectory of your project source.

If you use Git, try installing git-subtree, so you can easily use this repository for subtree merges, updating simply.

For the initial checkout:

cd projectdir

git subtree add --squash --prefix=cmake [email protected]:bilke/cmake-modules.git master

For updates:

cd projectdir

git subtree pull --squash --prefix=cmake [email protected]:bilke/cmake-modules.git master

For pushing to upstream:

cd projectdir

git subtree push --prefix=cmake [email protected]:bilke/cmake-modules.git master

How to Use

At the minimum, all you have to do is add a line like this near the top of your root CMakeLists.txt file (but not before your project() call):

list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")

Licenses

The modules that are written by Ryan Pavlik are all subject to this license:

Copyright Iowa State University 2009-2011

Distributed under the Boost Software License, Version 1.0.

(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

Modules based on those included with CMake as well as modules added by me (Lars Bilke) are under the OSI-approved BSD license, which is included in each of those modules. A few other modules are modified from other sources - when in doubt, look at the .cmake.

Important License Note!

If you find this file inside of another project, rather at the top-level directory, you're in a separate project that is making use of these modules. That separate project can (and probably does) have its own license specifics.

Comments
  • CodeCoverage: Some enhancements to reporting, tooling

    CodeCoverage: Some enhancements to reporting, tooling

    This adds a few enhancements to CodeCoverage.cmake that address issues I hit while integrating it into our build tree. Specifically:

    • Remove the Python detection completely, since it can sabotage the run if the Python version chosen by CMake isn't the correct one for gcovr.
    • Add a BASE_DIRECTORY argument to all setup_*() functions, which sets the base dir of the report.
      • Previously gcovr always used PROJECT_SOURCE_DIR, and lcov wasn't setting the basedir at all. Now all three will default to PROJECT_SOURCE_DIR, but can be overridden.
      • Setting the lcov basedir allows the --no-external option to work properly if passed in via LCOV_ARGS.
    • Add automatic addition of --demangle-cpp to the genhtml command line, iff a c++filt executable is found on the system.
      • This can be overridden by passing NO_DEMANGLE to setup_target_for_coverage_lcov().
    • Major enhancements to exclude processing:
      • The COVERAGE_LCOV_EXCLUDES and COVERAGE_GCOVR_EXCLUDES variables are now deprecated in favor of COVERAGE_EXCLUDES, which will be used by both.
      • All setup_*() functions also now take a multi-value argument, EXCLUDE, to specify exclude patterns instead of using the COVERAGE_EXCLUDES variable.
      • CMake 3.4+ only: Exclude patterns (specified via any means) can now be relative to the BASE_DIRECTORY, instead of having to be absolute paths. (This requires a version of CMake where get_filename_component() accepts the BASE_DIR argument.)
    • Add CMake configuration to clean up the .info file and the report output directory on 'make clean'.

    That last one makes me feel a bit better about the tool's housekeeping. Though TBH, I'd really love to be able to set the gcov output files as GENERATED so that CMake will clean those up as well. I just can't seem to find a reasonable way to do that, without resorting to ugly globbing or the like.

    opened by ferdnyc 16
  • CodeCoverage: exclude stdlib / boost headers from coverage report?

    CodeCoverage: exclude stdlib / boost headers from coverage report?

    It seems to me like there is currently no practical way to exclude e.g. all boost headers from the final coverage report, COVERAGE_EXCLUDES can only exclude files, not whole directories. This really clutters up the coverage report, making it essentially useless. Is there a workaround for this?

    EDIT: one method that works but kind of seems like a hack is the following:

    file(GLOB_RECURSE excludes "/usr/include/c++/*")                               
    set(COVERAGE_EXCLUDES "${excludes}")   
    

    I'm not sure how to do this in a platform-independant way though.

    opened by Time0o 8
  • CodeCoverage: Use VERBATIM for target commands

    CodeCoverage: Use VERBATIM for target commands

    @lieser raised a remaining issue in #28 with the coverage excludes, specifically that special characters (wildcards) aren't making it to the coverage commands because they're not properly quoted/escaped.

    This PR adds VERBATIM to theadd_custom_target() call for all three coverage modes, ensuring that CMake will protect all of the arguments on the COMMAND lines used to execute the tools.

    Fixes: #28

    opened by ferdnyc 7
  • Optional gcov

    Optional gcov

    It is currently difficult to use the module on environment that do not support gcov in the sens that including the file will just crash the build. The only alternative is to duplicate the environments tests in CodeCoverrage.cmake into the caller and only include if support is present. This patch propose to make a faulty environment non fatal, but only provide the functionalities if it's present. The caller can then use the variable COVERAGE_SUPPORTED

    if (CMAKE_BUILD_TYPE STREQUAL "Debug")
      include(CodeCoverage)
      if (COVERAGE_SUPPORTED)
        append_coverage_compiler_flags(--coverage)
        set(COVERAGE_EXCLUDES /opt /usr)
        setup_target_for_coverage(
          NAME cover
          EXECUTABLE ctest  
          DEPENDENCIES)
        message(INFO "run \"make cover\" to get coverage status.")
      endif()
    endif()
    
    opened by aminiussi 4
  • Out of source cmake build : unable to find *.gcno files

    Out of source cmake build : unable to find *.gcno files

    Hi,

    I am attempting to use the CodeCoverage.cmake macros for an out of source build of a C++ application using Boost unit_test_framework to drive the tests.

    As I am running the test on OS X, I have to use clang (4.1) as gcc does not support gcov.

    I am getting the following errors [100%] Resetting code coverage counters to zero. Processing code coverage counters and generating report. /opt/lcov/v1.10/bin/lcov --directory . --zerocounters Deleting all .da files in . and subdirectories Done. /Users/nicholas/temp/build_cpp/tests/unittest Running 1 test case...

    *** No errors detected /opt/lcov/v1.10/bin/lcov --directory . --capture --output-file unittest_coverage_output.info Capturing coverage data from . Found gcov version: 4.2.1 Scanning . for .gcda files ... Found 2 data files in . Processing compute.dir/Compute.cpp.gcda geninfo: ERROR: /Users/nicholas/temp/build_cpp/CMakeFiles/compute.dir/Compute.cpp.gcno: could not open file make[3]: *** [tests/CMakeFiles/UnitTestCoverage] Error 2 make[2]: *** [tests/CMakeFiles/UnitTestCoverage.dir/all] Error 2 make[1]: *** [tests/CMakeFiles/UnitTestCoverage.dir/rule] Error 2 make: *** [UnitTestCoverage] Error 2

    The following files location may shed some light

    Tan-Meng-Yues-MacBook:build_cpp nicholas$ find . -name *.gcno ./src/CMakeFiles/compute.dir/Compute.cpp.gcno ./tests/CMakeFiles/unittest.dir/main.cpp.gcno Tan-Meng-Yues-MacBook:build_cpp nicholas$ find . -name *.gcda ./CMakeFiles/compute.dir/Compute.cpp.gcda ./CMakeFiles/unittest.dir/main.cpp.gcda

    Cheers

    opened by nyue 4
  • Is there a way to specify environment variables when running LCOV_EXEC_TESTS_CMD?

    Is there a way to specify environment variables when running LCOV_EXEC_TESTS_CMD?

    In add_custom_target,

        add_custom_target(${Coverage_NAME}
            COMMAND ${LCOV_CLEAN_CMD}
            COMMAND ${LCOV_BASELINE_CMD} 
            COMMAND ${LCOV_EXEC_TESTS_CMD}
            COMMAND ${LCOV_CAPTURE_CMD}
            COMMAND ${LCOV_BASELINE_COUNT_CMD}
            COMMAND ${LCOV_FILTER_CMD} 
            COMMAND ${LCOV_GEN_HTML_CMD}
    

    ${LCOV_EXEC_TESTS_CMD} is resolved to the full path of the executable. However, when I changed the COMMAND to something like

    COMMAND ${Coverage_ENV_VAR} ${LCOV_EXEC_TESTS_CMD}
    

    Then ${LCOV_EXEC_TESTS_CMD} does not get resolved to the full path.

    opened by ahtsan 3
  • Improve support for multi project builds

    Improve support for multi project builds

    The module currently does not support testing code coverage when several subdirectories are built from a project/build directory, i.e:

    project/ | build/ | | CMakeLists.txt (top-level, builds all subprojects) | subproject1/ | | CMakeLists.txt | | src/ | | lib/ | other subprojects/

    Calling SETUP_TARGET_FOR_COVERAGE_GCOVR_(XML/HTML) within a subproject's CMakeLists.txt and building from the top level points gcovr's root directory to project/build, so the generated coverage report is empty. This PR changes the root directory to point to project/subproject and allows gcovr to generate a correct coverage report for the subproject.

    opened by jeffk95 3
  • Specify the output file for lcov --remove as an absolute path.

    Specify the output file for lcov --remove as an absolute path.

    For some reason,lcov --remove ... --outputfile <file>will try to open <file> wrt lcov location (I might have something to do with having . in your PATH).

    There are two possible workarounds for this problem

    • do not use --output-file but redirect the output instead
    • explicitly put that file into ${CMAKE_BINARY_DIR} (or another directory, maybe ${CMAKE_CURRENT_BINARY_DIR} ?)
    opened by aminiussi 3
  • Code comment for CodeCoverage.cmake is missleading

    Code comment for CodeCoverage.cmake is missleading

    Hi,

    For test coverage the parameter "Param _testrunner The name of the target which runs the tests" is misleading, it is not the target but a command with arguments, in which for cmake via make generator would be something like "make test".

    Is there a reason for not being a cmake target and added as a dependency ? flexibility ?

    ...
    # Param _testrunner     The name of the target which runs the tests.
    #						MUST return ZERO always, even on errors.
    #						If not, no coverage report will be created!
    ...
    FUNCTION(SETUP_TARGET_FOR_COVERAGE _targetname _testrunner _outputname)
    ...
    	SEPARATE_ARGUMENTS(test_command UNIX_COMMAND "${_testrunner}")
    
    	# Setup target
    	ADD_CUSTOM_TARGET(${_targetname}
    
    		# Cleanup lcov
    		${LCOV_PATH} --directory . --zerocounters
    
    		# Run tests
    		COMMAND ${test_command} ${ARGV3}
    ...
    	)
    

    Thanks

    opened by mjscosta 3
  • Code coverage verbose mode and way to add additional gcovr arguments

    Code coverage verbose mode and way to add additional gcovr arguments

    I added an additional CODE_COVERAGE_VERBOSE option to add additional output to the CMake configuration. This includes printing all the run LCOV commands so they can be verified if there are issues.

    opened by robamu 2
  • [CodeCoverage]: Fix issues with CodeCoverage and ninja

    [CodeCoverage]: Fix issues with CodeCoverage and ninja

    • Add -fprofile-abs-path to make gcno files contain absolute paths
    • Fix BASE_DIRECTORY not working when defined
    • Change BYPRODUCT from folder to index.html to stop ninja from complaining about double defines

    Closes #50

    opened by mdavis777 2
  • Always Error ' make (e=5): Access is denied'

    Always Error ' make (e=5): Access is denied'

    I have tried gcovr 3.2/4.8/5.1. And I use this CMake to use gcovr in my project. but when i execute 'make coverage' command. It always give below error back: C:\Downloads\gcovr-3.2\gcovr -r C:/Test/src --object-dir= C:/Test/build -e test_* process_begin: CreateProcess(NULL, C:\Downloads\gcovr-3.2\gcovr -r C:/Test/src --object-dir= C:/Test/build -e test_*, ...) failed.

    ### make (e=5): Access is denied.

    Please help!!! As this problem really bother me for a long time!!!

    opened by Darwin-Li-001 0
  • CodeCoverage.cmake does not show the comments of the cutom_command

    CodeCoverage.cmake does not show the comments of the cutom_command

    Hi,

    first of all thanks a lot for your work. It spares me a lot of time!

    I'm using the CodeCoverage.cmake script and it works very well but the message associated with custom targets are not printed. I'm working with CMake version 3.22.1.

    I solved this by replacing the comment with:

          COMMAND ${CMAKE_COMMAND} -E echo "Lcov code coverage info report saved in ${Coverage_NAME}.info."
    

    Do you want a PR for this?

    opened by hippo91 1
  • Issue with append_coverage_compiler_flags_to_target (but with solution)

    Issue with append_coverage_compiler_flags_to_target (but with solution)

    Hi there and thanks for this amazing repo!

    I was trying to cleanup my coverage workflow and tried to replace append_coverage_compiler_flags with append_coverage_compiler_flags_to_target.

    Two problems came across:

    1. I needed to replace (CodeCoverage.cmake L717):
       target_compile_options(${name} PRIVATE ${COVERAGE_COMPILER_FLAGS})
      

      with:

       separate_arguments(_flag_list NATIVE_COMMAND "${COVERAGE_COMPILER_FLAGS}")
       target_compile_options(${name} PRIVATE ${_flag_list})
      

      Since the white spaces were not recognized to split the flags everything was append to -g which resulted in:

       error: unrecognized debug output level ' -fprofile-arcs -ftest-coverage'
      
    2. Doing the above, I got another error, because the lib was not linked against gcov. So I could solve this by replacing:
      append_coverage_compiler_flags_to_target(${LIB_NAME})
      

      with:

      target_compile_options(${LIB_NAME} PRIVATE -g --coverage)
      target_link_libraries(${LIB_NAME} PRIVATE gcov)
      

    Note, that --coverage is equivalent to -fprofile-arcs -ftest-coverage (when compiling) and -lgcov (when linking). link

    Maybe it could be a good idea to replace:

    function(append_coverage_compiler_flags_to_target name)
        target_compile_options(${name}
            PRIVATE ${COVERAGE_COMPILER_FLAGS})
    endfunction()
    

    with

    function(append_coverage_compiler_flags_to_target name)
        separate_arguments(_flag_list NATIVE_COMMAND "${COVERAGE_COMPILER_FLAGS}")
        target_compile_options(${name} PRIVATE ${_flag_list})
        target_link_libraries(${name} PRIVATE gcov)
    endfunction()
    

    And maybe we could also replace -fprofile-arcs -ftest-coverage with --coverage.

    Cheers, Sebastian

    opened by MuellerSeb 0
  • Support for INCLUDE arg as opposed to EXCLUDE ?

    Support for INCLUDE arg as opposed to EXCLUDE ?

    This is a tiny feature request :) It would be real handy if there is support for an INCLUDE argument to setup_target_for_coverage_*. It becomes a bit annoying if I have a quite a bit of source files, but just want to see the coverage for a particular class.

    Thank you.

    opened by sakthi-vivek 1
  • EXCLUDEs additional directories which starts with the same name

    EXCLUDEs additional directories which starts with the same name

    Hello,

    # Folder structure
    .
    |-- src/
    |-- test/
    |-- testmodules/
    |-- CMakeLists.txt
    
    setup_target_for_coverage_gcovr_html(
            NAME ${PROJECT_NAME}_coverage_html
            EXECUTABLE ${PROJECT_NAME} --gtest_output=xml:report.xml
            BASE_DIRECTORY ${CMAKE_SOURCE_DIR}
            EXCLUDE "test/*")
    

    In the above example, the testmodules also get excluded even if it was just the test folder that I wanted to exclude.

    Any help is appreciated. Thank you.

    opened by sakthi-vivek 4
  • Add support for sonar?

    Add support for sonar?

    I manually modified CodeCoverage.cmake to include:

    `function(setup_target_for_coverage_gcovr_sonar)

    set(options NONE)
    set(oneValueArgs BASE_DIRECTORY NAME)
    set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
    cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
    
    if(NOT GCOVR_PATH)
        message(FATAL_ERROR "gcovr not found! Aborting...")
    endif() # NOT GCOVR_PATH
    
    # Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
    if(DEFINED Coverage_BASE_DIRECTORY)
        get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
    else()
        set(BASEDIR ${PROJECT_SOURCE_DIR})
    endif()
    
    # Collect excludes (CMake 3.4+: Also compute absolute paths)
    set(GCOVR_EXCLUDES "")
    foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
        if(CMAKE_VERSION VERSION_GREATER 3.4)
            get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
        endif()
        list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
    endforeach()
    list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
    
    # Combine excludes to several -e arguments
    set(GCOVR_EXCLUDE_ARGS "")
    foreach(EXCLUDE ${GCOVR_EXCLUDES})
        list(APPEND GCOVR_EXCLUDE_ARGS "-e")
        list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
    endforeach()
    
    # Set up commands which will be run to generate coverage data
    # Run tests
    set(GCOVR_XML_EXEC_TESTS_CMD
        ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
    )
    # Running gcovr
    set(GCOVR_XML_CMD
        ${GCOVR_PATH} -r ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS} ${GCOVR_EXCLUDE_ARGS} 
        --object-directory=${PROJECT_BINARY_DIR} --sonar ${Coverage_NAME}.xml
    )
    
    if(CODE_COVERAGE_VERBOSE)
        message(STATUS "Executed command report")
    
        message(STATUS "Command to run tests: ")
        string(REPLACE ";" " " GCOVR_XML_EXEC_TESTS_CMD_SPACED "${GCOVR_XML_EXEC_TESTS_CMD}")
        message(STATUS "${GCOVR_XML_EXEC_TESTS_CMD_SPACED}")
    
        message(STATUS "Command to generate gcovr XML coverage data: ")
        string(REPLACE ";" " " GCOVR_XML_CMD_SPACED "${GCOVR_XML_CMD}")
        message(STATUS "${GCOVR_XML_CMD_SPACED}")
    endif()
    
    add_custom_target(${Coverage_NAME}
        COMMAND ${GCOVR_XML_EXEC_TESTS_CMD}
        COMMAND ${GCOVR_XML_CMD}
        
        BYPRODUCTS ${Coverage_NAME}.xml
        WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
        DEPENDS ${Coverage_DEPENDENCIES}
        VERBATIM # Protect arguments to commands
        COMMENT "Running gcovr to produce Sonar code coverage report."
    )
    
    # Show info where to find the report
    add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
        COMMAND ;
        COMMENT "Sonar code coverage report saved in ${Coverage_NAME}.xml."
    )
    

    endfunction() # setup_target_for_coverage_sonar_xml `

    opened by KantarBruceAdams 0
Owner
Lars Bilke
Lars Bilke
CMake checks cache helper modules – for fast CI CMake builds!

cmake-checks-cache Cross platform CMake projects do platform introspection by the means of "Check" macros. Have a look at CMake's How To Write Platfor

Cristian Adam 60 Aug 17, 2022
CMake modules to help use sanitizers

sanitizers-cmake CMake module to enable sanitizers for binary targets. Include into your project To use FindSanitizers.cmake, simply add this reposito

Matt Arsenault 285 Sep 21, 2022
CMake Community Modules

CMake Community Modules The CMake Community Modules are CMake modules created and maintained by the community. This repository's main product is the C

Edgar 1 May 12, 2022
Extra CMake Modules for YARP and friends

YCM Extra CMake Modules for YARP and friends Documentation Online documentation is available

Robotology 42 Sep 12, 2022
Extra modules and scripts for CMake.

Extra CMake Modules Introduction The Extra CMake Modules package, or ECM, adds to the modules provided by CMake, including ones used by find_package()

KDE GitHub Mirror 101 Sep 23, 2022
CMake modules for some scientific libraries

A collection of CMake modules, which can mostly be used independently. The utilities for writing robust Find* modules might be useful until CMake take

Jed Brown 80 Jul 12, 2022
Common CMake modules

CMake Modules This repository contains common CMake modules and a collection of find scripts to locate non-CMake dependencies. The recommended way to

Eyescale Software GmbH 144 Sep 21, 2022
A set of cmake modules to assist in building code

CMake 3 Tools Warning: These tools are being replaced by the Modern CMake. Some of the tools are still being maintained for now, but new projects shou

null 190 Sep 19, 2022
📦 CMake's missing package manager. A small CMake script for setup-free, cross-platform, reproducible dependency management.

Setup-free CMake dependency management CPM.cmake is a CMake script that adds dependency management capabilities to CMake. It's built as a thin wrapper

CPM.cmake 1.3k Sep 21, 2022
CMake scripts for painless usage of SuiteSparse+METIS from Visual Studio and the rest of Windows/Linux/OSX IDEs supported by CMake

CMake scripts for painless usage of Tim Davis' SuiteSparse (CHOLMOD,UMFPACK,AMD,LDL,SPQR,...) and METIS from Visual Studio and the rest of Windows/Lin

Jose Luis Blanco-Claraco 388 Sep 16, 2022
cmake-font-lock - Advanced, type aware, highlight support for CMake

cmake-font-lock - Advanced, type aware, highlight support for CMake

Anders Lindgren 37 Dec 30, 2021
cmake-avr - a cmake toolchain for AVR projects

cmake-avr - a cmake toolchain for AVR projects Testing the example provided The toolchain was created and tested within the following environment: Lin

Matthias Kleemann 160 Sep 5, 2022
Make CMake less painful when trying to write Modern Flexible CMake

Izzy's eXtension Modules IXM is a CMake library for writing Modern flexible CMake. This means: Reducing the amount of CMake written Selecting reasonab

IXM 107 Sep 1, 2022
CMake module to enable code coverage easily and generate coverage reports with CMake targets.

CMake-codecov CMake module to enable code coverage easily and generate coverage reports with CMake targets. Include into your project To use Findcodec

HPC 79 Sep 12, 2022
unmaintained - CMake module to activate certain C++ standard, feature checks and appropriate automated workarounds - basically an improved version of cmake-compile-features

Compatibility This library provides an advanced target_compile_features() and write_compiler_detection_header(). The problem with those is that they a

Jonathan Müller 72 Apr 14, 2022
[CMake] [BSD-2] CMake module to find ICU

FindICU.cmake A CMake module to find International Components for Unicode (ICU) Library Note that CMake, since its version 3.7.0, includes a FindICU m

julp 28 Sep 1, 2022
A fast build system that encourages the creation of small, reusable modules over a variety of platforms and languages.

Buck Buck is a build tool. To see what Buck can do for you, check out the documentation at http://buck.build/. Installation Since Buck is used to buil

Facebook 8.4k Sep 22, 2022
CMake project for BL602 RISC-V processor

bl602_cmake_base CMake project for BL602 RISC-V processor How to build NOTE : This project uses a pre-compiled version of the Buffalo SDK (bl_iot_sdk)

null 9 Jan 6, 2022
A CMake toolchain file for iOS, macOS, watchOS & tvOS C/C++/Obj-C++ development

A CMake toolchain file for iOS, macOS, watchOS & tvOS C/C++/Obj-C++ development

Alexander Widerberg 1.4k Sep 23, 2022