1========== 2Clang-Tidy 3========== 4 5.. contents:: 6 7See also: 8 9.. toctree:: 10 :maxdepth: 1 11 12 List of Clang-Tidy Checks <checks/list> 13 Clang-tidy IDE/Editor Integrations <Integrations> 14 Getting Involved <Contributing> 15 External Clang-Tidy Examples <ExternalClang-TidyExamples> 16 17:program:`clang-tidy` is a clang-based C++ "linter" tool. Its purpose is to 18provide an extensible framework for diagnosing and fixing typical programming 19errors, like style violations, interface misuse, or bugs that can be deduced via 20static analysis. :program:`clang-tidy` is modular and provides a convenient 21interface for writing new checks. 22 23 24Using Clang-Tidy 25================ 26 27:program:`clang-tidy` is a `LibTooling`_-based tool, and it's easier to work 28with if you set up a compile command database for your project (for an example 29of how to do this, see `How To Setup Tooling For LLVM`_). You can also specify 30compilation options on the command line after ``--``: 31 32.. code-block:: console 33 34 $ clang-tidy test.cpp -- -Imy_project/include -DMY_DEFINES ... 35 36If there are too many options or source files to specify on the command line, 37you can store them in a parameter file, and use :program:`clang-tidy` with that 38parameters file: 39 40.. code-block:: console 41 42 $ clang-tidy @parameters_file 43 44:program:`clang-tidy` has its own checks and can also run Clang Static Analyzer 45checks. Each check has a name and the checks to run can be chosen using the 46``-checks=`` option, which specifies a comma-separated list of positive and 47negative (prefixed with ``-``) globs. Positive globs add subsets of checks, and 48negative globs remove them. For example, 49 50.. code-block:: console 51 52 $ clang-tidy test.cpp -checks=-*,clang-analyzer-*,-clang-analyzer-cplusplus* 53 54will disable all default checks (``-*``) and enable all ``clang-analyzer-*`` 55checks except for ``clang-analyzer-cplusplus*`` ones. 56 57The ``-list-checks`` option lists all the enabled checks. When used without 58``-checks=``, it shows checks enabled by default. Use ``-checks=*`` to see all 59available checks or with any other value of ``-checks=`` to see which checks are 60enabled by this value. 61 62.. _checks-groups-table: 63 64There are currently the following groups of checks: 65 66====================== ========================================================= 67Name prefix Description 68====================== ========================================================= 69``abseil-`` Checks related to Abseil library. 70``altera-`` Checks related to OpenCL programming for FPGAs. 71``android-`` Checks related to Android. 72``boost-`` Checks related to Boost library. 73``bugprone-`` Checks that target bug-prone code constructs. 74``cert-`` Checks related to CERT Secure Coding Guidelines. 75``clang-analyzer-`` Clang Static Analyzer checks. 76``concurrency-`` Checks related to concurrent programming (including 77 threads, fibers, coroutines, etc.). 78``cppcoreguidelines-`` Checks related to C++ Core Guidelines. 79``darwin-`` Checks related to Darwin coding conventions. 80``fuchsia-`` Checks related to Fuchsia coding conventions. 81``google-`` Checks related to Google coding conventions. 82``hicpp-`` Checks related to High Integrity C++ Coding Standard. 83``linuxkernel-`` Checks related to the Linux Kernel coding conventions. 84``llvm-`` Checks related to the LLVM coding conventions. 85``llvmlibc-`` Checks related to the LLVM-libc coding standards. 86``misc-`` Checks that we didn't have a better category for. 87``modernize-`` Checks that advocate usage of modern (currently "modern" 88 means "C++11") language constructs. 89``mpi-`` Checks related to MPI (Message Passing Interface). 90``objc-`` Checks related to Objective-C coding conventions. 91``openmp-`` Checks related to OpenMP API. 92``performance-`` Checks that target performance-related issues. 93``portability-`` Checks that target portability-related issues that don't 94 relate to any particular coding style. 95``readability-`` Checks that target readability-related issues that don't 96 relate to any particular coding style. 97``zircon-`` Checks related to Zircon kernel coding conventions. 98====================== ========================================================= 99 100Clang diagnostics are treated in a similar way as check diagnostics. Clang 101diagnostics are displayed by :program:`clang-tidy` and can be filtered out using 102the ``-checks=`` option. However, the ``-checks=`` option does not affect 103compilation arguments, so it cannot turn on Clang warnings which are not 104already turned on in the build configuration. The ``-warnings-as-errors=`` 105option upgrades any warnings emitted under the ``-checks=`` flag to errors (but 106it does not enable any checks itself). 107 108Clang diagnostics have check names starting with ``clang-diagnostic-``. 109Diagnostics which have a corresponding warning option, are named 110``clang-diagnostic-<warning-option>``, e.g. Clang warning controlled by 111``-Wliteral-conversion`` will be reported with check name 112``clang-diagnostic-literal-conversion``. 113 114The ``-fix`` flag instructs :program:`clang-tidy` to fix found errors if 115supported by corresponding checks. 116 117An overview of all the command-line options: 118 119.. code-block:: console 120 121 $ clang-tidy --help 122 USAGE: clang-tidy [options] <source0> [... <sourceN>] 123 124 OPTIONS: 125 126 Generic Options: 127 128 --help - Display available options (--help-hidden for more) 129 --help-list - Display list of available options (--help-list-hidden for more) 130 --version - Display the version of this program 131 132 clang-tidy options: 133 134 --checks=<string> - Comma-separated list of globs with optional '-' 135 prefix. Globs are processed in order of 136 appearance in the list. Globs without '-' 137 prefix add checks with matching names to the 138 set, globs with the '-' prefix remove checks 139 with matching names from the set of enabled 140 checks. This option's value is appended to the 141 value of the 'Checks' option in .clang-tidy 142 file, if any. 143 --config=<string> - Specifies a configuration in YAML/JSON format: 144 -config="{Checks: '*', 145 CheckOptions: {x: y}}" 146 When the value is empty, clang-tidy will 147 attempt to find a file named .clang-tidy for 148 each source file in its parent directories. 149 --config-file=<string> - Specify the path of .clang-tidy or custom config file: 150 e.g. --config-file=/some/path/myTidyConfigFile 151 This option internally works exactly the same way as 152 --config option after reading specified config file. 153 Use either --config-file or --config, not both. 154 --dump-config - Dumps configuration in the YAML format to 155 stdout. This option can be used along with a 156 file name (and '--' if the file is outside of a 157 project with configured compilation database). 158 The configuration used for this file will be 159 printed. 160 Use along with -checks=* to include 161 configuration of all checks. 162 --enable-check-profile - Enable per-check timing profiles, and print a 163 report to stderr. 164 --enable-module-headers-parsing - Enables preprocessor-level module header parsing 165 for C++20 and above, empowering specific checks 166 to detect macro definitions within modules. This 167 feature may cause performance and parsing issues 168 and is therefore considered experimental. 169 --exclude-header-filter=<string> - Regular expression matching the names of the 170 headers to exclude diagnostics from. Diagnostics 171 from the main file of each translation unit are 172 always displayed. 173 Must be used together with --header-filter. 174 Can be used together with -line-filter. 175 This option overrides the 'ExcludeHeaderFilterRegex' 176 option in .clang-tidy file, if any. 177 --explain-config - For each enabled check explains, where it is 178 enabled, i.e. in clang-tidy binary, command 179 line or a specific configuration file. 180 --export-fixes=<filename> - YAML file to store suggested fixes in. The 181 stored fixes can be applied to the input source 182 code with clang-apply-replacements. 183 --extra-arg=<string> - Additional argument to append to the compiler command line 184 --extra-arg-before=<string> - Additional argument to prepend to the compiler command line 185 --fix - Apply suggested fixes. Without -fix-errors 186 clang-tidy will bail out if any compilation 187 errors were found. 188 --fix-errors - Apply suggested fixes even if compilation 189 errors were found. If compiler errors have 190 attached fix-its, clang-tidy will apply them as 191 well. 192 --fix-notes - If a warning has no fix, but a single fix can 193 be found through an associated diagnostic note, 194 apply the fix. 195 Specifying this flag will implicitly enable the 196 '--fix' flag. 197 --format-style=<string> - Style for formatting code around applied fixes: 198 - 'none' (default) turns off formatting 199 - 'file' (literally 'file', not a placeholder) 200 uses .clang-format file in the closest parent 201 directory 202 - '{ <json> }' specifies options inline, e.g. 203 -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' 204 - 'llvm', 'google', 'webkit', 'mozilla' 205 See clang-format documentation for the up-to-date 206 information about formatting styles and options. 207 This option overrides the 'FormatStyle` option in 208 .clang-tidy file, if any. 209 --header-filter=<string> - Regular expression matching the names of the 210 headers to output diagnostics from. Diagnostics 211 from the main file of each translation unit are 212 always displayed. 213 Can be used together with -line-filter. 214 This option overrides the 'HeaderFilterRegex' 215 option in .clang-tidy file, if any. 216 --line-filter=<string> - List of files with line ranges to filter the 217 warnings. Can be used together with 218 -header-filter. The format of the list is a 219 JSON array of objects: 220 [ 221 {"name":"file1.cpp","lines":[[1,3],[5,7]]}, 222 {"name":"file2.h"} 223 ] 224 --list-checks - List all enabled checks and exit. Use with 225 -checks=* to list all available checks. 226 --load=<pluginfilename> - Load the specified plugin 227 -p <string> - Build path 228 --quiet - Run clang-tidy in quiet mode. This suppresses 229 printing statistics about ignored warnings and 230 warnings treated as errors if the respective 231 options are specified. 232 --store-check-profile=<prefix> - By default reports are printed in tabulated 233 format to stderr. When this option is passed, 234 these per-TU profiles are instead stored as JSON. 235 --system-headers - Display the errors from system headers. 236 This option overrides the 'SystemHeaders' option 237 in .clang-tidy file, if any. 238 --use-color - Use colors in diagnostics. If not set, colors 239 will be used if the terminal connected to 240 standard output supports colors. 241 This option overrides the 'UseColor' option in 242 .clang-tidy file, if any. 243 --verify-config - Check the config files to ensure each check and 244 option is recognized. 245 --vfsoverlay=<filename> - Overlay the virtual filesystem described by file 246 over the real file system. 247 --warnings-as-errors=<string> - Upgrades warnings to errors. Same format as 248 '-checks'. 249 This option's value is appended to the value of 250 the 'WarningsAsErrors' option in .clang-tidy 251 file, if any. 252 --allow-no-checks - Allow empty enabled checks. This suppresses 253 the "no checks enabled" error when disabling 254 all of the checks. 255 256 -p <build-path> is used to read a compile command database. 257 258 For example, it can be a CMake build directory in which a file named 259 compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON 260 CMake option to get this output). When no build path is specified, 261 a search for compile_commands.json will be attempted through all 262 parent paths of the first input file . See: 263 https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an 264 example of setting up Clang Tooling on a source tree. 265 266 <source0> ... specify the paths of source files. These paths are 267 looked up in the compile command database. If the path of a file is 268 absolute, it needs to point into CMake's source tree. If the path is 269 relative, the current working directory needs to be in the CMake 270 source tree and the file must be in a subdirectory of the current 271 working directory. "./" prefixes in the relative files will be 272 automatically removed, but the rest of a relative path must be a 273 suffix of a path in the compile command database. 274 275 Parameters files: 276 A large number of options or source files can be passed as parameter files 277 by use '@parameter-file' in the command line. 278 279 Configuration files: 280 clang-tidy attempts to read configuration for each source file from a 281 .clang-tidy file located in the closest parent directory of the source 282 file. The .clang-tidy file is specified in YAML format. If any configuration 283 options have a corresponding command-line option, command-line option takes 284 precedence. 285 286 The following configuration options may be used in a .clang-tidy file: 287 288 CheckOptions - List of key-value pairs defining check-specific 289 options. Example: 290 CheckOptions: 291 some-check.SomeOption: 'some value' 292 Checks - Same as '--checks'. Additionally, the list of 293 globs can be specified as a list instead of a 294 string. 295 ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'. 296 ExtraArgs - Same as '--extra-arg'. 297 ExtraArgsBefore - Same as '--extra-arg-before'. 298 FormatStyle - Same as '--format-style'. 299 HeaderFileExtensions - File extensions to consider to determine if a 300 given diagnostic is located in a header file. 301 HeaderFilterRegex - Same as '--header-filter'. 302 ImplementationFileExtensions - File extensions to consider to determine if a 303 given diagnostic is located in an 304 implementation file. 305 InheritParentConfig - If this option is true in a config file, the 306 configuration file in the parent directory 307 (if any exists) will be taken and the current 308 config file will be applied on top of the 309 parent one. 310 SystemHeaders - Same as '--system-headers'. 311 UseColor - Same as '--use-color'. 312 User - Specifies the name or e-mail of the user 313 running clang-tidy. This option is used, for 314 example, to place the correct user name in 315 TODO() comments in the relevant check. 316 WarningsAsErrors - Same as '--warnings-as-errors'. 317 318 The effective configuration can be inspected using --dump-config: 319 320 $ clang-tidy --dump-config 321 --- 322 Checks: '-*,some-check' 323 WarningsAsErrors: '' 324 HeaderFileExtensions: ['', 'h','hh','hpp','hxx'] 325 ImplementationFileExtensions: ['c','cc','cpp','cxx'] 326 HeaderFilterRegex: '' 327 FormatStyle: none 328 InheritParentConfig: true 329 User: user 330 CheckOptions: 331 some-check.SomeOption: 'some value' 332 ... 333 334.. _clang-tidy-nolint: 335 336Suppressing Undesired Diagnostics 337================================= 338 339:program:`clang-tidy` diagnostics are intended to call out code that does not 340adhere to a coding standard, or is otherwise problematic in some way. However, 341if the code is known to be correct, it may be useful to silence the warning. 342Some clang-tidy checks provide a check-specific way to silence the diagnostics, 343e.g. `bugprone-use-after-move <checks/bugprone/use-after-move.html>`_ can be 344silenced by re-initializing the variable after it has been moved out, 345`bugprone-string-integer-assignment 346<checks/bugprone/string-integer-assignment.html>`_ can be suppressed by 347explicitly casting the integer to ``char``, 348`readability-implicit-bool-conversion 349<checks/readability/implicit-bool-conversion.html>`_ can also be suppressed by 350using explicit casts, etc. 351 352If a specific suppression mechanism is not available for a certain warning, or 353its use is not desired for some reason, :program:`clang-tidy` has a generic 354mechanism to suppress diagnostics using ``NOLINT``, ``NOLINTNEXTLINE``, and 355``NOLINTBEGIN`` ... ``NOLINTEND`` comments. 356 357The ``NOLINT`` comment instructs :program:`clang-tidy` to ignore warnings on the 358*same line* (it doesn't apply to a function, a block of code or any other 359language construct; it applies to the line of code it is on). If introducing the 360comment on the same line would change the formatting in an undesired way, the 361``NOLINTNEXTLINE`` comment allows suppressing clang-tidy warnings on the *next 362line*. The ``NOLINTBEGIN`` and ``NOLINTEND`` comments allow suppressing 363clang-tidy warnings on *multiple lines* (affecting all lines between the two 364comments). 365 366All comments can be followed by an optional list of check names in parentheses 367(see below for the formal syntax). The list of check names supports globbing, 368with the same format and semantics as for enabling checks. Note: negative globs 369are ignored here, as they would effectively re-activate the warning. 370 371For example: 372 373.. code-block:: c++ 374 375 class Foo { 376 // Suppress all the diagnostics for the line 377 Foo(int param); // NOLINT 378 379 // Consider explaining the motivation to suppress the warning 380 Foo(char param); // NOLINT: Allow implicit conversion from `char`, because <some valid reason> 381 382 // Silence only the specified checks for the line 383 Foo(double param); // NOLINT(google-explicit-constructor, google-runtime-int) 384 385 // Silence all checks from the `google` module 386 Foo(bool param); // NOLINT(google*) 387 388 // Silence all checks ending with `-avoid-c-arrays` 389 int array[10]; // NOLINT(*-avoid-c-arrays) 390 391 // Silence only the specified diagnostics for the next line 392 // NOLINTNEXTLINE(google-explicit-constructor, google-runtime-int) 393 Foo(bool param); 394 395 // Silence all checks from the `google` module for the next line 396 // NOLINTNEXTLINE(google*) 397 Foo(bool param); 398 399 // Silence all checks ending with `-avoid-c-arrays` for the next line 400 // NOLINTNEXTLINE(*-avoid-c-arrays) 401 int array[10]; 402 403 // Silence only the specified checks for all lines between the BEGIN and END 404 // NOLINTBEGIN(google-explicit-constructor, google-runtime-int) 405 Foo(short param); 406 Foo(long param); 407 // NOLINTEND(google-explicit-constructor, google-runtime-int) 408 409 // Silence all checks from the `google` module for all lines between the BEGIN and END 410 // NOLINTBEGIN(google*) 411 Foo(bool param); 412 // NOLINTEND(google*) 413 414 // Silence all checks ending with `-avoid-c-arrays` for all lines between the BEGIN and END 415 // NOLINTBEGIN(*-avoid-c-arrays) 416 int array[10]; 417 // NOLINTEND(*-avoid-c-arrays) 418 }; 419 420The formal syntax of ``NOLINT``, ``NOLINTNEXTLINE``, and ``NOLINTBEGIN`` ... 421``NOLINTEND`` is the following: 422 423.. parsed-literal:: 424 425 lint-comment: 426 lint-command 427 lint-command lint-args 428 429 lint-args: 430 **(** check-name-list **)** 431 432 check-name-list: 433 *check-name* 434 check-name-list **,** *check-name* 435 436 lint-command: 437 **NOLINT** 438 **NOLINTNEXTLINE** 439 **NOLINTBEGIN** 440 **NOLINTEND** 441 442Note that whitespaces between 443``NOLINT``/``NOLINTNEXTLINE``/``NOLINTBEGIN``/``NOLINTEND`` and the opening 444parenthesis are not allowed (in this case the comment will be treated just as 445``NOLINT``/``NOLINTNEXTLINE``/``NOLINTBEGIN``/``NOLINTEND``), whereas in the 446check names list (inside the parentheses), whitespaces can be used and will be 447ignored. 448 449All ``NOLINTBEGIN`` comments must be paired by an equal number of ``NOLINTEND`` 450comments. Moreover, a pair of comments must have matching arguments -- for 451example, ``NOLINTBEGIN(check-name)`` can be paired with 452``NOLINTEND(check-name)`` but not with ``NOLINTEND`` `(zero arguments)`. 453:program:`clang-tidy` will generate a ``clang-tidy-nolint`` error diagnostic if 454any ``NOLINTBEGIN``/``NOLINTEND`` comment violates these requirements. 455 456.. _LibTooling: https://clang.llvm.org/docs/LibTooling.html 457.. _How To Setup Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html 458