在Ubuntu上进行C++代码覆盖率分析,可以使用以下几种工具和方法:
安装gcov和lcov:
sudo apt-get install gcc g makes
sudo apt-get install gcc-multilib g-multilib
sudo apt-get install lcov
编译代码:
在编译时添加 -fprofile-arcs -ftest-coverage
选项以启用代码覆盖率分析。
g++ -fprofile-arcs -ftest-coverage -o my_program my_program.cpp
运行程序:
执行生成的可执行文件以收集覆盖率数据。
./my_program
生成覆盖率报告:
使用 lcov
生成HTML格式的覆盖率报告。
lcov --capture --directory . --output-file coverage.info
genhtml coverage.info --output-directory coverage_report
查看报告:
使用浏览器打开 coverage_report/index.html
文件以查看代码覆盖率报告。
安装pytest和pytest-cov:
pip install pytest pytest-cov
编写测试用例:
创建测试文件,例如 test_calculator.py
。
运行测试并生成覆盖率报告:
使用 pytest
运行测试并生成覆盖率报告。
pytest --cov=src tests/
生成HTML格式的详细报告:
pytest --cov=src --cov-report=html tests/
安装Visual Studio Code和C/C++插件以及Gcov Viewer插件。
配置tasks.json文件:
在 .vscode
文件夹下创建 tasks.json
文件,并配置编译任务以启用代码覆盖率分析。
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "g++",
"args": [
"-fprofile-arcs",
"-ftest-coverage",
"-fPIC",
"-O0",
"${fileDirname}/*.cpp",
"-o",
"${fileDirname}/main"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": []
}
]
}
生成覆盖率报告:
编译并运行程序后,在Visual Studio Code中按下 Ctrl+Shift+P
打开命令面板,输入 gcov
点击 Gcov Viewer: Show
即可成功显示覆盖率。
以上方法可以帮助您在Ubuntu上进行C++代码覆盖率分析,选择适合您项目和工作流程的工具进行使用。