cppcheck静态扫描未使用接口说明

0.工具介绍#

cppcheck是一款开源的静态代码分析工具,用于检查C和C++代码中的编程错误。cppcheck可以发现代码中的内存泄漏、未初始化变量、使用后释放指针、数组越界访问、类型强制转换错误等常见错误。

以下是一些常用的命令及其说明:

1. --project=<project_file>:对整个项目进行检查,需要提供一个包含所有源文件路径的项目文件,项目文件可以是 Visual Studio 解决方案 (.sln)、Visual Studio 项目 (.vcxproj)、编译数据库 (compile_commands.json) 或 Borland C++ Builder 6 (*.bpr) 文件。在指定的文件中,要分析的文件、包含路径、定义、平台和未定义项将被使用。
2. --platform=<type>, 指定平台特定的类型和大小。部分可用的内置平台如下:
   - unix32: 32位Unix变体
   - unix64: 64位Unix变体
   - win32A: 32位Windows ASCII字符编码
   - win32W: 32位Windows UNICODE字符编码
   - win64: 64位Windows
3. --enable=all :启用所有检查
4. --enable=warning :只启用警告级别的检查
5. --enable=performance:只启用性能相关的检查
6. --enable=style :只启用风格相关的检查
7. --enable=unusedFunction:只启用未使用函数的相关检查
8. --xml-version=2 :将结果以XML格式输出
9. --output-file=result.txt :将结果输出到指定文件

下面以Ubuntu系统为例进行操作。

1.安装cppcheck#

确认系统网络可对外通信,使用命令sudo apt install cppcheck,即可完成工具安装。

2.确认待测项目#

将待测项目拷贝到Ubuntu的任一目录下,其中最好包含测试用例,以减少工具误报。

3.开始检测#

若项目的相对路径为./TestProject,则使用命令,cppcheck --enable=unusedFunction --output-file=result.c --force ./TestProject/,cppcheck会将结果输出到当前目录的result.c中。

需要注意,cppcheck将进度信息写入标准输出流(stdout),而将错误输出写入标准错误流(stderr), 若需要手动将结果输出至文件时,重定向命令需要使用2>

终端的部分输出如下所示:

Checking BSP_AM64X_ARMv8/testCase_A53/test_timer.c ...
172/173 files checked 99% done
Checking BSP_AM64X_ARMv8/testCase_A53/test_uart.c ...
173/173 files checked 100% done

部分检测到的错误输出结果如下所示:

BSP_AM64X_ARMv8/driver/board_init.c:63:0:  The function 'time_init' is never used. [unusedFunction]

^
BSP_AM64X_ARMv8/testCase_A53/test_timer.c:50:0:  The function 'timer_demo' is never used. [unusedFunction]

^
BSP_AM64X_ARMv8/driver/net/enet/core/lwipif/src/tx_test.c:202:0:  The function 'tx_test0' is never used. [unusedFunction]

^
BSP_AM64X_ARMv8/driver/serial/uart16550.c:1017:0:  The function 'uart_dump' is never used. [unusedFunction]

4.处理结果#

直接输出的结果并不方便查询与阅读,所以需要对结果进行处理,使用以下代码创建python文件,本例创建文件名为extract_strings.py,接下来使用命令python ./extract_strings.py ./result.c output.txt ,即可在将上一步的输出结果result.c文件格式化,并输出到同目录下的output.txt中。

import sys

if len(sys.argv) != 3:
    # 如果参数不正确,则输出提示信息并退出程序
    print("Input arg error! Usage: python extract_strings.py <input_file_path> <output_file_path>")
    sys.exit(1)

input_file_path = sys.argv[1]
output_file_path = sys.argv[2]

# 使用with语句打开输入文件和输出文件,自动关闭文件流
with open(input_file_path, 'r') as input_file, open(output_file_path, 'w') as output_file:
    for line in input_file:
        # 去掉每行开头和结尾的空格和换行符
        line = line.strip()
        start = line.find("'")
        end = line.rfind("'")
        if start != -1 and end != -1 and start != end:
            output_file.write(line[start+1:end] + "\n")

print("Extract strings sucess, output:", output_file_path)

output.txt内的部分结果如下所示,可对比第3步所示的错误信息:

time_init
timer_demo
tx_test0
uart_dump
posted @   Yangtai  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示
主题色彩