You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

clang-tidy是否有检测直接传入字面量数值参数的linter配置?

clang-tidy 检测/限制函数调用直接传入数字字面量的配置方案

你需要使用clang-tidy的readability-magic-numbers规则,该规则专门用于识别代码中无命名的“魔法数字”,刚好覆盖你提到的函数参数场景。

配置方法

在项目根目录的.clang-tidy配置文件中添加如下内容:

# 启用规则
Checks: +readability-magic-numbers
# 规则参数配置
CheckOptions:
  # 核心配置:关闭函数参数忽略,所有直接传入函数的数字字面量都会被检测
  - key: readability-magic-numbers.IgnoreFunctionArguments
    value: false
  # 可选配置:忽略枚举值、宏、常量变量中的数字字面量,避免误报
  - key: readability-magic-numbers.IgnoreEnumValues
    value: true
  - key: readability-magic-numbers.IgnoreMacros
    value: true
  - key: readability-magic-numbers.IgnoreConstVariables
    value: true
  # 可选配置:如果需要放行部分常用字面量(比如0、1),可以在这里配置
  # - key: readability-magic-numbers.IgnoreIntegerValues
  #   value: '0,1'

效果说明

  • 不良写法 socket(0, 0, 0) 会直接触发该规则的报错提示,要求替换为具名变量
  • 先定义int domain = 0; int type = 0; int protocol = 0;再传入的写法,不会触发规则,符合要求

命令行临时调用方式

如果不需要写配置文件,临时检测单个文件可以用如下命令:

clang-tidy --checks=+readability-magic-numbers \
  --config='{CheckOptions: [{key: readability-magic-numbers.IgnoreFunctionArguments, value: false}]}' \
  your_source_code.cpp

如果部分场景确实需要直接传字面量,可以在对应代码行末尾加// NOLINT(readability-magic-numbers)跳过检测即可。

内容的提问来源于stack exchange,提问作者Mikhail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 05:45:03