安装lcov genhtml
sudo apt-get install lcov
sudo apt-get install lcov-genhtml
生成.gcno
调试信息文件
编译代码并添加-fprofile-arcs
和-ftest-coverage
选项。例如,对于一个名为map_client_lib
的目标,可以在CMakeLists.txt
文件中添加以下行。编译后会生成.gcno
文件,即编译器生成的调试信息。
target_compile_options(map_client_lib PUBLIC -fprofile-arcs -ftest-coverage)
执行单元测试,生成.gcda
覆盖率信息文件
运行单元测试。在运行测试之前,确保已经生成了代码调试信息文件,运行后会生成.gcda
覆盖率信息文件。
使用lcov
命令收集覆盖率信息
lcov --directory ./build/ --capture --output-file temp.info
# 简化版
lcov -c -d ./build -o temp.info
去掉多余的目录如:/opt/* /usr/*等
lcov --remove temp.info "/opt/*" "/usr/*" "*/.conan2/*" "*/build/*" -o coverage.info
生成HTML覆盖率报告
genhtml coverage.info -o html
一键执行脚本
#!/bin/bash
app_path=xxx
build_dir=./build/
current_time=$(date +"%Y-%m-%d_%H:%M:%S")
echo $current_time
$app_path
# Define the function to generate the coverage report
generate_coverage_report() {
lcov --directory $build_dir --capture --output-file temp.info
lcov --remove temp.info "/opt/*" "/usr/*" "*/.conan2/*" "*/build/*" -o coverage_$current_time.info
genhtml coverage_$current_time.info -o html_$current_time
}
# Call the function to generate the coverage report
generate_coverage_report
# Copy the HTML report to the "html" directory
rm -rf html
cp -r html_$current_time html
# Remove the temporary files
rm temp.info