目录
C++ 如何进行代码覆盖率统计?通过 lcov 这个工具。
参考:
步骤:
1. 安装 lcov
Gcov是一个测试 C++ 代码覆盖率的程序。
Lcov 则是 gcov 结果展现的一个可视化工具,可以将覆盖率信息以 HTML 方式展现。
Lcov 下载地址:LCOV - the LTP GCOV extension
Mac 安装 lcov 命令:
brew install lcov
2. 添加编译参数
在 CMakeLists 中添加覆盖率编译参数:
# 添加覆盖率编译参数
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")
然后编译、运行程序。
3. 统计覆盖率
执行 lcov 命令以统计覆盖率:
lcov --directory . --capture --output-file coverage.info
4. 可视化
genhtml -o result coverage.info
result 是一个覆盖率统计结果可视化目录,其中的 index.html 为导航页面。
脚本
覆盖率统计脚本示例:
echo "覆盖率统计..."
rm -rf ./覆盖率结果/
lcov --capture --directory ./ --output-file coverage.info || exit
# 移除不需要统计的文件
lcov --remove coverage.info '*/test/*' '*/ThirdPartyLayer/*' '/usr/include/*' -o result.info || exit
# 可视化
genhtml coverage.info --output-directory ./覆盖率结果/ || exit