clang-tidy

21 篇文章 0 订阅
5 篇文章 0 订阅

Clang-Tidy 简介


其他:

clang-tidy是一个基于clang的c++“linter”工具。它的目的是提供一个可扩展的框架,用于诊断和修复典型的编程错误,如样式违反接口滥用或通过静态分析可以推断出的错误。Clang-tidy是模块化的,为写新检查规则提供了一个方便的接口

clang-tidy 用法

clang-tidy是一个基于LibTooling的工具,如果你为项目设置了一个编译命令数据库,那么使用clang-tidy会更容易(有关如何做到这一点的示例,请参阅 How To Setup Tooling For LLVM)。你也可以在命令行加入--:之后指定编译选项。

$ clang-tidy test.cpp -- -Imy_project/include -DMY_DEFINES ...

Clang-tidy有自己的检查,也可以运行Clang静态分析器检查。每个检查都有一个名称,可以使用-checks= option选择要运行的检查,该选项指定一个用逗号分隔的glob和-glob(以-为前缀)列表。+glob添加检查子集,-glob则不检查。例如,

$ clang-tidy test.cpp -checks=-*,clang-analyzer-*,-clang-analyzer-cplusplus*

(-*)将禁用所有默认检查,clang-analyzer-*启用所有检查,并除去clang-analyzer-cplusplus*检查。

-list-checks选项列出所有启用的检查。当不带-checks=使用时,它显示默认启用的检查。

$ clang-tidy -list-checks 

使用-checks=“*”查看所有可用的检查,

$ clang-tidy -list-checks -checks="*"

或者使用-checks=的任何其他值查看由该值启用的检查。

$ clang-tidy -list-checks -checks="-*,abseil-*"

生成配置文件

$ clang-tidy -checks="*" --dump-config > .clang-tidy

目前有以下几组checks:

Name prefixDescription备注
abseil-Checks related to Abseil library.Abseil library是 google 开源的 C++通用库,其目标是作为标准库的补充。
altera-Checks related to OpenCL programming for FPGAs.
android-Checks related to Android.
boost-Checks related to Boost library.
bugprone-Checks that target bug-prone code constructs.
cert-Checks related to CERT Secure Coding Guidelines.SEI CERT Coding Standards,简称 CERT,是 CMU(Carnegie Mellon University)软件工程研究所(SEI)发布的 C/C++ 编码规范,专注于安全问题,适合与其他规范配合使用。
clang-analyzer-Clang Static Analyzer checks.
concurrency-Checks related to concurrent programming (including threads, fibers, coroutines, etc.).并发编程
cppcoreguidelines-Checks related to C++ Core Guidelines.C++ Core Guidelines,[中文版],简称 CCG,是 C++ 创始人对 C++ 代码编写的宏观指导,属于语言级规范体系,全面地阐述了现代 C++ 编程思想,以规则条款的形式明确地指出哪些是要避免的,哪些是值得提倡的,具有权威性,适合开发者学习。
darwin-Checks related to Darwin coding conventions.Darwin 是 Apple 开源系统
fuchsia-Checks related to Fuchsia coding conventions.Fuchsia是谷歌研发的操作系统
google-Checks related to Google coding conventions.
hicpp-Checks related to High Integrity C++ Coding Standard.High Integrity C++ Coding Standard,历史悠久的 C/C++ 规范体系,现归属于 Perforce Software, Inc.,提供独特而有效的方法提升代码质量并规避风险,被多种知名规范参考引用,而且还提供合规性审计软件,但并不侧重于安全问题,适合与 SEI CERT 等安全类规范配合使用。
linuxkernel-Checks related to the Linux Kernel coding conventions.
llvm-Checks related to the LLVM coding conventions.
llvmlibc-Checks related to the LLVM-libc coding standards.
misc-Checks that we didn’t have a better category for.
modernize-Checks that advocate usage of modern (currently “modern” means “C++11”) language constructs.
mpi-Checks related to MPI (Message Passing Interface).
objc-Checks related to Objective-C coding conventions.Objective-C 用于Apple软件开发
openmp-Checks related to OpenMP API.OpenAPI 规范(OAS),是定义一个标准的、与具体编程语言无关的RESTful API的规范。OpenAPI 规范使得人类和计算机都能在“不接触任何程序源代码和文档、不监控网络通信”的情况下理解一个服务的作用。如果您在定义您的 API 时做的很好,那么使用 API 的人就能非常轻松地理解您提供的 API 并与之交互了。
如果您遵循 OpenAPI 规范来定义您的 API,那么您就可以用文档生成工具来展示您的 API,用代码生成工具来自动生成各种编程语言的服务器端和客户端的代码,用自动测试工具进行测试等等。
performance-Checks that target performance-related issues.

Clang检查的处理方式和check检查类似。Clang检查由Clang-tidy显示,可以使用-checks=选项过滤掉。然而 -checks=选项不影响编译参数,因此它不能打开在编译配置中尚未打开的Clang警告。-warnings-as-errors= 选项将-checks= 标志下发出的任何警告升级为错误(但它本身不启用任何检查)。
Clang 检查的规则名称以clang-diagnostic-开头。具有相应警告选项的检查规则称为clang-diagnostic-,例如:由-Wliteral-conversion 控制的Clang警告将通过检查名clang-diagnostic-literal-conversion报告。
-fix标志指示clang-tidy修复发现的错误,如果相应的检查规则支持的话。
所有命令行选项的概述:

$ clang-tidy --help
USAGE: clang-tidy [options] <source0> [... <sourceN>]

OPTIONS:

Generic Options:

  --help                         - Display available options (--help-hidden for more)
  --help-list                    - Display list of available options (--help-list-hidden for more)
  --version                      - Display the version of this program

clang-tidy options:

  --checks=<string>              -
                                   Comma-separated list of globs with optional '-'
                                   prefix. Globs are processed in order of
                                   appearance in the list. Globs without '-'
                                   prefix add checks with matching names to the
                                   set, globs with the '-' prefix remove checks
                                   with matching names from the set of enabled
                                   checks. This option's value is appended to the
                                   value of the 'Checks' option in .clang-tidy
                                   file, if any.
                                   翻译:
                                   用逗号分隔的glob列表,带有可选的'-'前缀。glob按照出现在列表中的顺
                                   序处理。没有“-”前缀则添加检	查,带有'-'前缀的则删除相应检查。选
                                   项的值会被附加到.clang-tidy配置文件中的'Checks'选项,如果有的话。
  --config=<string>              -
                                   Specifies a configuration in YAML/JSON format:
                                     -config="{Checks: '*',
                                               CheckOptions: {x, y}}"
                                   When the value is empty, clang-tidy will
                                   attempt to find a file named .clang-tidy for
                                   each source file in its parent directories.
                                   翻译:
                                   指定配置的格式为YAML/JSON :
                                   -config="{Checks: '*',CheckOptions: {x, y}}"  当值为空时,
                                   clang-tidy将尝试在父目录中的每个源文件中找到一个名为.clang-tidy的
                                   文件。
  --config-file=<string>         -
                                  Specify the path of .clang-tidy or custom config file:
                                    e.g. --config-file=/some/path/myTidyConfigFile
                                  This option internally works exactly the same way as
                                    --config option after reading specified config file.
                                  Use either --config-file or --config, not both.
                                  翻译:
                                  指定.clang-tidy或自定义配置文件的路径:
                                  例如,--config-file=/some/path/myTidyConfigFile
                                  此选项在内部的工作方式与读取指定的配置文件后选择--config选项一样。
                                  使用--config-file或--config中的任意一个,而不是两者都使用。
  --dump-config                  -
                                   Dumps configuration in the YAML format to
                                   stdout. This option can be used along with a
                                   file name (and '--' if the file is outside of a
                                   project with configured compilation database).
                                   The configuration used for this file will be
                                   printed.
                                   Use along with -checks=* to include
                                   configuration of all checks.
                                   翻译:
                                   将YAML格式的配置转储到stdout。该选项可与文件名(如果文件位于
                                   配置了编译数据库的项目外面)。用于此文件的配置将被打印出来。
                                   与-checks=*一起使用来包含所有检查的配置。

  --enable-check-profile         -
                                   Enable per-check timing profiles, and print a
                                   report to stderr.
                                   翻译:
                                   启用每次检查计时配置文件,并打印报告到stderr。
  --explain-config               -
                                   For each enabled check explains, where it is
                                   enabled, i.e. in clang-tidy binary, command
                                   line or a specific configuration file.
                                   翻译:
                                   对于每个启用的检查说明它的位置启用,也就是说,在clang-tidy的二进
                                   制文件中,命令行或特定的配置文件。
                                   
  --export-fixes=<filename>      -
                                   YAML file to store suggested fixes in. The
                                   stored fixes can be applied to the input source
                                   code with clang-apply-replacements.
                                   翻译:
                                   YAML文件来存储建议的修复。这些 存储的修正可以应用到输入的源代码中


  --extra-arg=<string>           - Additional argument to append to the compiler command line.
                                   Can be used several times.
                                   翻译:
                                   要追加到编译器命令行的附加参数。可以多次使用。
                                   
  --extra-arg-before=<string>    - Additional argument to prepend to the compiler command line.
                                   Can be used several times.
                                    翻译:
                                   要追加到编译器命令行的附加参数。可以多次使用。                                  
  --fix                          -
                                   Apply suggested fixes. Without -fix-errors
                                   clang-tidy will bail out if any compilation
                                   errors were found.
                                   翻译:
                                   应用建议的修复。如果没有 -fix-errors clang-tidy会在发现任何编译 
                                   错误时跳过。
  --fix-errors                   -
                                   Apply suggested fixes even if compilation
                                   errors were found. If compiler errors have
                                   attached fix-its, clang-tidy will apply them as
                                   well.
                                   翻译:
                                   即使发现编译错误,也要应用建议的修复方法。如果编译器错
                                   误有 附带的修复程序,clang-tidy也会应用。
  --fix-notes                    -
                                   If a warning has no fix, but a single fix can
                                   be found through an associated diagnostic note,
                                   apply the fix.
                                   Specifying this flag will implicitly enable the
                                   '--fix' flag.
                                   翻译:
                                   如果一个警告没有修复,但通过相关的诊断说明可以找到一个单一的修复,
                                   应用该修复。 指定这个标志将隐含地启用 '--fix'标志。
  --format-style=<string>        -
                                   Style for formatting code around applied fixes:
                                     - 'none' (default) turns off formatting
                                     - 'file' (literally 'file', not a placeholder)
                                       uses .clang-format file in the closest parent
                                       directory
                                     - '{ <json> }' specifies options inline, e.g.
                                       -format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
                                     - 'llvm', 'google', 'webkit', 'mozilla'
                                   See clang-format documentation for the up-to-date
                                   information about formatting styles and options.
                                   This option overrides the 'FormatStyle` option in
                                   .clang-tidy file, if any.


  --header-filter=<string>       -
                                   Regular expression matching the names of the
                                   headers to output diagnostics from. Diagnostics
                                   from the main file of each translation unit are
                                   always displayed.
                                   Can be used together with -line-filter.
                                   This option overrides the 'HeaderFilterRegex'
                                   option in .clang-tidy file, if any.
                                   翻译:
                                   匹配头文件名称的正则表达式,用于输出诊断程序。每个翻译单元的主文件
                                   中的诊断总是显示出来。
                                   可与-line-filter一起使用。这个选项覆盖'HeaderFilterRegex'
                                   选项在.clang-tidy文件中,如果有的话。

  --line-filter=<string>         -
                                   List of files with line ranges to filter the
                                   warnings. Can be used together with
                                   -header-filter. The format of the list is a
                                   JSON array of objects:
                                     [
                                       {"name":"file1.cpp","lines":[[1,3],[5,7]]},
                                       {"name":"file2.h"}
                                     ]
                                    翻译:
                                    带有行数范围的文件列表,用于过滤警告。可以和 -header-filter一起
                                    用。该列表的格式是一个JSON数组的对象。
                                    
  --list-checks                  -
                                   List all enabled checks and exit. Use with
                                   -checks=* to list all available checks.
                                   翻译:
                                   列出所有已启用的检查并退出。使用-checks=*来列出所有可用的检查。
  -load=<plugin>                 -
                                   Load the dynamic object ``plugin``. This
                                   object should register new static analyzer
                                   or clang-tidy passes. Once loaded, the
                                   object will add new command line options
                                   to run various analyses. To see the new
                                   complete list of passes, use the
                                   :option:`--list-checks` and
                                   :option:`-load` options together.
                                   翻译:
                                   加载动态对象“插件”。这个对象应该注册新的静态分析器或clang-tidy通
                                   道。一旦加载,对象将添加新的命令行选项来运行各种分析。要查看新的完
                                   整的通过列表, 可以同时使用
                                   :option:`--list-checks`和
                                   :option:-load'选项。
                                  
  -p <string>                    - Build path
  --quiet                        -
                                   Run clang-tidy in quiet mode. This suppresses
                                   printing statistics about ignored warnings and
                                   warnings treated as errors if the respective
                                   options are specified.
                                   翻译:
                                   在安静模式下运行clang-tidy。如果指定了相应的选项,则禁止打印关于
                                   被忽略的警告和被视为错误的警告的统计信息。
  --store-check-profile=<prefix> -
                                   By default reports are printed in tabulated
                                   format to stderr. When this option is passed,
                                   these per-TU profiles are instead stored as JSON.
                                   翻译:
                                   默认情况下,报告以表格格式打印到stderr。当传递此选项时,这些每个
                                   TU的概要文件将被存储为JSON。
	

  --system-headers               - Display the errors from system headers.
  
  --use-color                    -
                                  Use colors in diagnostics. If not set, colors
                                  will be used if the terminal connected to
                                  standard output supports colors.
                                  This option overrides the 'UseColor' option in
                                  .clang-tidy file, if any.
                                  翻译:
                                  在诊断中使用颜色。如果没有设置,如果连接到标准输出的终端支持颜色,
                                  将使用颜色。
                                  这个选项覆盖clang-tidy文件中的'UseColor'选项(如果有的话)。

  --verify-config                -
                                   Check the config files to ensure each check and
                                   option is recognized.
                                   翻译:
                                   检查配置文件,确保每个检查和选项都被识别。
  --vfsoverlay=<filename>        -
                                   Overlay the virtual filesystem described by file
                                   over the real file system.
                                  	翻译:
                                  	将文件描述的虚拟文件系统覆盖在真实的文件系统上。
  --warnings-as-errors=<string>  -
                                   Upgrades warnings to errors. Same format as
                                   '-checks'.
                                   This option's value is appended to the value of
                                   the 'WarningsAsErrors' option in .clang-tidy
                                   file, if any.
                                   翻译:
                                   将警告升级为错误。格式与'-checks'相同。该选项的值被附加到
                                   .clang-tidy文件中的'WarningsAsErrors'选项的值(如果有的话)。
                                   

-p <build-path> is used to read a compile command database.
		
        For example, it can be a CMake build directory in which a file named
        compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
        CMake option to get this output). When no build path is specified,
        a search for compile_commands.json will be attempted through all
        parent paths of the first input file . See:
        https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an
        example of setting up Clang Tooling on a source tree.
        翻译:
        -p <build-path>用于读取编译命令数据库。
        例如,它可以是一个CMake构建目录,其中包含一个名为compile_commands.json 的文件。
        (使用-DCMAKE_EXPORT_COMPILE_COMMANDS=ON CMake选项来获得此输出)。
        当没有指定构建路径时,将尝试通过第一个输入文件的所有父路径搜索compile_commands.json。
        有关在源代码树上设置Clang Tooling 的示例,
        请参见:https://clang.1lvm.org/docs/HowToSetupToolingForLLVM.html。

<source0> ... specify the paths of source files. These paths are
        looked up in the compile command database. If the path of a file is
        absolute, it needs to point into CMake's source tree. If the path is
        relative, the current working directory needs to be in the CMake
        source tree and the file must be in a subdirectory of the current
        working directory. "./" prefixes in the relative files will be
        automatically removed, but the rest of a relative path must be a
        suffix of a path in the compile command database.
		翻译:
		<source0>...指定源文件的路径。这些路径在编译命令数据库中查找。如果文件的路径是绝对的,它需要指向CMake的源树。如果路径是相对的,则当前工作目录需要在CMake源代码树中,而文件必须在当前工作目录的一个子路径。相对文件中的"./"前缀将被自动删除,但相对路径的其余部分必须是编译命令数据库中路径的后缀。

Configuration files:
  clang-tidy attempts to read configuration for each source file from a
  .clang-tidy file located in the closest parent directory of the source
  file. If InheritParentConfig is true in a config file, the configuration file
  in the parent directory (if any exists) will be taken and current config file
  will be applied on top of the parent one. If any configuration options have
  a corresponding command-line option, command-line option takes precedence.
  The effective configuration can be inspected using -dump-config:
翻译:
Clang-tidy尝试从位于源文件最近的父目录中读取每个源文件的配置的.Clang-tidy。如果配置文件中的InheritParentconfig为true,则父目录中的配置文件(如果存在的话)将被取走,并将当前配置文件应用到父目录之上。如果任何配置选项都有相应的命令行选项,则命令行选项优先。有效的配置可以使用-dump-config命令检查:
    $ clang-tidy -dump-config
    ---
    Checks:              '-*,some-check'
    WarningsAsErrors:    ''
    HeaderFilterRegex:   ''
    FormatStyle:         none
    InheritParentConfig: true
    User:                user
    CheckOptions:
      some-check.SomeOption: 'some value'

屏蔽不想要的检查

Clang-tidy旨在诊断调用不符合编码标准的代码,或在某些方面存在其他问题的代码。但是,如果已知代码是正确的,则可以将警告静音。一些clang-tidy检查提供了一种特定于检查的方法来抑制诊断,例如, bugprone-use-after-move 可以通过在移出变量后重新初始化变量来抑制, bugprone-string-integer-assignment 可以通过显式将整数转换为char来抑制, readability-implicit-bool-conversion也可以通过显式转换来抑制。

如果特定的抑制机制对于某个警告不可用,或者由于某种原因不希望使用它,clang-tidy有一个通用机制来抑制诊断:使用NOLINT, NOLINTNEXTLINE, and NOLINTBEGINNOLINTEND注释。
NOLINT 注释指示clang-tidy忽略同一行上的警告(它不应用于函数、代码块或任何其他语言结构;它适用于它所在的代码行)。如果在同一行中引入注释会以不希望的方式更改格式,NOLINTNEXTLINE注释允许在下一行中抑制clat -tidy警告。NOLINTBEGINNOLINTEND注释允许在多行上抑制clang-tidy警告(影响两个注释之间的所有行)。

所有注释后面都可以有一个括号内的可选检查名列表(参见下面的正式语法)。检查名称列表支持globbing,其格式和语义与启用检查相同。注意:负值的glob在这里被忽略,因为它们将有效地重新激活警告。
For example:

class Foo {
  // Suppress all the diagnostics for the line
  Foo(int param); // NOLINT

  // Consider explaining the motivation to suppress the warning
  Foo(char param); // NOLINT: Allow implicit conversion from `char`, because <some valid reason>

  // Silence only the specified checks for the line
  Foo(double param); // NOLINT(google-explicit-constructor, google-runtime-int)

  // Silence all checks from the `google` module
  Foo(bool param); // NOLINT(google*)

  // Silence all checks ending with `-avoid-c-arrays`
  int array[10]; // NOLINT(*-avoid-c-arrays)

  // Silence only the specified diagnostics for the next line
  // NOLINTNEXTLINE(google-explicit-constructor, google-runtime-int)
  Foo(bool param);

  // Silence all checks from the `google` module for the next line
  // NOLINTNEXTLINE(google*)
  Foo(bool param);

  // Silence all checks ending with `-avoid-c-arrays` for the next line
  // NOLINTNEXTLINE(*-avoid-c-arrays)
  int array[10];

  // Silence only the specified checks for all lines between the BEGIN and END
  // NOLINTBEGIN(google-explicit-constructor, google-runtime-int)
  Foo(short param);
  Foo(long param);
  // NOLINTEND(google-explicit-constructor, google-runtime-int)

  // Silence all checks from the `google` module for all lines between the BEGIN and END
  // NOLINTBEGIN(google*)
  Foo(bool param);
  // NOLINTEND(google*)

  // Silence all checks ending with `-avoid-c-arrays` for all lines between the BEGIN and END
  // NOLINTBEGIN(*-avoid-c-arrays)
  int array[10];
  // NOLINTEND(*-avoid-c-arrays)
};

NOLINT, NOLINTNEXTLINENOLINTBEGINNOLINTEND的正式语法如下:

lint-comment:
  lint-command
  lint-command lint-args

lint-args:
  ( check-name-list )

check-name-list:
  check-name
  check-name-list , check-name

lint-command:
  NOLINT
  NOLINTNEXTLINE
  NOLINTBEGIN
  NOLINTEND

注意中间的空白NOLINT/NOLINTNEXTLINE/NOLINTBEGIN/NOLINTEND 和开括号是不允许的(在这种情况下注释将被视为NOLINT/NOLINTNEXTLINE/NOLINTBEGIN/NOLINTEND),而在检查名称列表中(在括号内),可以使用空格并将被忽略。
所有NOLINTBEGIN 注释必须与相同数量的NOLINTEND 注释配对。此外,一对注释必须有匹配的实参——例如,NOLINTBEGIN(check-name)可以与NOLINTEND(check-name)配对,但不能与NOLINTEND (zero arguments)配对。如果任何 NOLINTBEGIN/NOLINTEND 注释违反了这些要求,clang-tidy将生成一个clang-tidy-nolint错误诊断。

参考资料:

  1. Clang-Tidy — Extra Clang Tools 16.0.0git documentation (llvm.org)
  2. Apple 开源系统 Darwin 的历史 - 知乎 (zhihu.com)
  3. CERT Secure Coding Standard — C语言安全编程规范_IT_老杨的博客-CSDN博客_cert-c
  4. SEI CERT Coding Standards - CERT Secure Coding - Confluence (cmu.edu)
  5. zh-cn/contribute/OpenHarmony-c-coding-style-guide.md · OpenHarmony/docs - 码云 - 开源中国 (gitee.com)
  6. zh-cn/contribute/OpenHarmony-cpp-coding-style-guide.md · OpenHarmony/docs - 码云 - 开源中国 (gitee.com)
  7. LLVM基本概念入门 - 知乎 (zhihu.com)
  8. OpenAPI 规范 (中文版) (apifox.cn)
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值