• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1==========
2Clang-Tidy
3==========
4
5.. contents::
6
7See also:
8
9.. toctree::
10   :maxdepth: 1
11
12   The list of clang-tidy checks <checks/list>
13   Clang-tidy IDE/Editor Integrations <Integrations>
14   Getting Involved <Contributing>
15
16:program:`clang-tidy` is a clang-based C++ "linter" tool. Its purpose is to
17provide an extensible framework for diagnosing and fixing typical programming
18errors, like style violations, interface misuse, or bugs that can be deduced via
19static analysis. :program:`clang-tidy` is modular and provides a convenient
20interface for writing new checks.
21
22
23Using clang-tidy
24================
25
26:program:`clang-tidy` is a `LibTooling`_-based tool, and it's easier to work
27with if you set up a compile command database for your project (for an example
28of how to do this see `How To Setup Tooling For LLVM`_). You can also specify
29compilation options on the command line after ``--``:
30
31.. code-block:: console
32
33  $ clang-tidy test.cpp -- -Imy_project/include -DMY_DEFINES ...
34
35:program:`clang-tidy` has its own checks and can also run Clang static analyzer
36checks. Each check has a name and the checks to run can be chosen using the
37``-checks=`` option, which specifies a comma-separated list of positive and
38negative (prefixed with ``-``) globs. Positive globs add subsets of checks,
39negative globs remove them. For example,
40
41.. code-block:: console
42
43  $ clang-tidy test.cpp -checks=-*,clang-analyzer-*,-clang-analyzer-cplusplus*
44
45will disable all default checks (``-*``) and enable all ``clang-analyzer-*``
46checks except for ``clang-analyzer-cplusplus*`` ones.
47
48The ``-list-checks`` option lists all the enabled checks. When used without
49``-checks=``, it shows checks enabled by default. Use ``-checks=*`` to see all
50available checks or with any other value of ``-checks=`` to see which checks are
51enabled by this value.
52
53.. _checks-groups-table:
54
55There are currently the following groups of checks:
56
57====================== =========================================================
58Name prefix            Description
59====================== =========================================================
60``abseil-``            Checks related to Abseil library.
61``altera-``            Checks related to OpenCL programming for FPGAs.
62``android-``           Checks related to Android.
63``boost-``             Checks related to Boost library.
64``bugprone-``          Checks that target bugprone code constructs.
65``cert-``              Checks related to CERT Secure Coding Guidelines.
66``clang-analyzer-``    Clang Static Analyzer checks.
67``concurrency-``       Checks related to concurrent programming (including
68                       threads, fibers, coroutines, etc.).
69``cppcoreguidelines-`` Checks related to C++ Core Guidelines.
70``darwin-``            Checks related to Darwin coding conventions.
71``fuchsia-``           Checks related to Fuchsia coding conventions.
72``google-``            Checks related to Google coding conventions.
73``hicpp-``             Checks related to High Integrity C++ Coding Standard.
74``linuxkernel-``       Checks related to the Linux Kernel coding conventions.
75``llvm-``              Checks related to the LLVM coding conventions.
76``llvmlibc-``          Checks related to the LLVM-libc coding standards.
77``misc-``              Checks that we didn't have a better category for.
78``modernize-``         Checks that advocate usage of modern (currently "modern"
79                       means "C++11") language constructs.
80``mpi-``               Checks related to MPI (Message Passing Interface).
81``objc-``              Checks related to Objective-C coding conventions.
82``openmp-``            Checks related to OpenMP API.
83``performance-``       Checks that target performance-related issues.
84``portability-``       Checks that target portability-related issues that don't
85                       relate to any particular coding style.
86``readability-``       Checks that target readability-related issues that don't
87                       relate to any particular coding style.
88``zircon-``            Checks related to Zircon kernel coding conventions.
89====================== =========================================================
90
91Clang diagnostics are treated in a similar way as check diagnostics. Clang
92diagnostics are displayed by :program:`clang-tidy` and can be filtered out using
93``-checks=`` option. However, the ``-checks=`` option does not affect
94compilation arguments, so it can not turn on Clang warnings which are not
95already turned on in build configuration. The ``-warnings-as-errors=`` option
96upgrades any warnings emitted under the ``-checks=`` flag to errors (but it
97does not enable any checks itself).
98
99Clang diagnostics have check names starting with ``clang-diagnostic-``.
100Diagnostics which have a corresponding warning option, are named
101``clang-diagnostic-<warning-option>``, e.g. Clang warning controlled by
102``-Wliteral-conversion`` will be reported with check name
103``clang-diagnostic-literal-conversion``.
104
105The ``-fix`` flag instructs :program:`clang-tidy` to fix found errors if
106supported by corresponding checks.
107
108An overview of all the command-line options:
109
110.. code-block:: console
111
112  $ clang-tidy --help
113  USAGE: clang-tidy [options] <source0> [... <sourceN>]
114
115  OPTIONS:
116
117  Generic Options:
118
119    --help                         - Display available options (--help-hidden for more)
120    --help-list                    - Display list of available options (--help-list-hidden for more)
121    --version                      - Display the version of this program
122
123  clang-tidy options:
124
125    --checks=<string>              -
126                                     Comma-separated list of globs with optional '-'
127                                     prefix. Globs are processed in order of
128                                     appearance in the list. Globs without '-'
129                                     prefix add checks with matching names to the
130                                     set, globs with the '-' prefix remove checks
131                                     with matching names from the set of enabled
132                                     checks. This option's value is appended to the
133                                     value of the 'Checks' option in .clang-tidy
134                                     file, if any.
135    --config=<string>              -
136                                     Specifies a configuration in YAML/JSON format:
137                                       -config="{Checks: '*',
138                                                 CheckOptions: [{key: x,
139                                                                 value: y}]}"
140                                     When the value is empty, clang-tidy will
141                                     attempt to find a file named .clang-tidy for
142                                     each source file in its parent directories.
143    --dump-config                  -
144                                     Dumps configuration in the YAML format to
145                                     stdout. This option can be used along with a
146                                     file name (and '--' if the file is outside of a
147                                     project with configured compilation database).
148                                     The configuration used for this file will be
149                                     printed.
150                                     Use along with -checks=* to include
151                                     configuration of all checks.
152    --enable-check-profile         -
153                                     Enable per-check timing profiles, and print a
154                                     report to stderr.
155    --explain-config               -
156                                     For each enabled check explains, where it is
157                                     enabled, i.e. in clang-tidy binary, command
158                                     line or a specific configuration file.
159    --export-fixes=<filename>      -
160                                     YAML file to store suggested fixes in. The
161                                     stored fixes can be applied to the input source
162                                     code with clang-apply-replacements.
163    --extra-arg=<string>           - Additional argument to append to the compiler command line
164                                     Can be used several times.
165    --extra-arg-before=<string>    - Additional argument to prepend to the compiler command line
166                                     Can be used several times.
167    --fix                          -
168                                     Apply suggested fixes. Without -fix-errors
169                                     clang-tidy will bail out if any compilation
170                                     errors were found.
171    --fix-errors                   -
172                                     Apply suggested fixes even if compilation
173                                     errors were found. If compiler errors have
174                                     attached fix-its, clang-tidy will apply them as
175                                     well.
176    --format-style=<string>        -
177                                     Style for formatting code around applied fixes:
178                                       - 'none' (default) turns off formatting
179                                       - 'file' (literally 'file', not a placeholder)
180                                         uses .clang-format file in the closest parent
181                                         directory
182                                       - '{ <json> }' specifies options inline, e.g.
183                                         -format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
184                                       - 'llvm', 'google', 'webkit', 'mozilla'
185                                     See clang-format documentation for the up-to-date
186                                     information about formatting styles and options.
187                                     This option overrides the 'FormatStyle` option in
188                                     .clang-tidy file, if any.
189    --header-filter=<string>       -
190                                     Regular expression matching the names of the
191                                     headers to output diagnostics from. Diagnostics
192                                     from the main file of each translation unit are
193                                     always displayed.
194                                     Can be used together with -line-filter.
195                                     This option overrides the 'HeaderFilterRegex'
196                                     option in .clang-tidy file, if any.
197    --line-filter=<string>         -
198                                     List of files with line ranges to filter the
199                                     warnings. Can be used together with
200                                     -header-filter. The format of the list is a
201                                     JSON array of objects:
202                                       [
203                                         {"name":"file1.cpp","lines":[[1,3],[5,7]]},
204                                         {"name":"file2.h"}
205                                       ]
206    --list-checks                  -
207                                     List all enabled checks and exit. Use with
208                                     -checks=* to list all available checks.
209    -p=<string>                    - Build path
210    --quiet                        -
211                                     Run clang-tidy in quiet mode. This suppresses
212                                     printing statistics about ignored warnings and
213                                     warnings treated as errors if the respective
214                                     options are specified.
215    --store-check-profile=<prefix> -
216                                     By default reports are printed in tabulated
217                                     format to stderr. When this option is passed,
218                                     these per-TU profiles are instead stored as JSON.
219    --system-headers               - Display the errors from system headers.
220    --vfsoverlay=<filename>        -
221                                     Overlay the virtual filesystem described by file
222                                     over the real file system.
223    --warnings-as-errors=<string>  -
224                                     Upgrades warnings to errors. Same format as
225                                     '-checks'.
226                                     This option's value is appended to the value of
227                                     the 'WarningsAsErrors' option in .clang-tidy
228                                     file, if any.
229
230  -p <build-path> is used to read a compile command database.
231
232          For example, it can be a CMake build directory in which a file named
233          compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
234          CMake option to get this output). When no build path is specified,
235          a search for compile_commands.json will be attempted through all
236          parent paths of the first input file . See:
237          https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an
238          example of setting up Clang Tooling on a source tree.
239
240  <source0> ... specify the paths of source files. These paths are
241          looked up in the compile command database. If the path of a file is
242          absolute, it needs to point into CMake's source tree. If the path is
243          relative, the current working directory needs to be in the CMake
244          source tree and the file must be in a subdirectory of the current
245          working directory. "./" prefixes in the relative files will be
246          automatically removed, but the rest of a relative path must be a
247          suffix of a path in the compile command database.
248
249
250  Configuration files:
251    clang-tidy attempts to read configuration for each source file from a
252    .clang-tidy file located in the closest parent directory of the source
253    file. If InheritParentConfig is true in a config file, the configuration file
254    in the parent directory (if any exists) will be taken and current config file
255    will be applied on top of the parent one. If any configuration options have
256    a corresponding command-line option, command-line option takes precedence.
257    The effective configuration can be inspected using -dump-config:
258
259      $ clang-tidy -dump-config
260      ---
261      Checks:              '-*,some-check'
262      WarningsAsErrors:    ''
263      HeaderFilterRegex:   ''
264      FormatStyle:         none
265      InheritParentConfig: true
266      User:                user
267      CheckOptions:
268        - key:             some-check.SomeOption
269          value:           'some value'
270      ...
271
272.. _clang-tidy-nolint:
273
274Suppressing Undesired Diagnostics
275=================================
276
277:program:`clang-tidy` diagnostics are intended to call out code that does not
278adhere to a coding standard, or is otherwise problematic in some way.  However,
279if the code is known to be correct, it may be useful to silence the warning.
280Some clang-tidy checks provide a check-specific way to silence the diagnostics,
281e.g.  `bugprone-use-after-move <checks/bugprone-use-after-move.html>`_ can be
282silenced by re-initializing the variable after it has been moved out,
283`bugprone-string-integer-assignment
284<checks/bugprone-string-integer-assignment.html>`_ can be suppressed by
285explicitly casting the integer to ``char``,
286`readability-implicit-bool-conversion
287<checks/readability-implicit-bool-conversion.html>`_ can also be suppressed by
288using explicit casts, etc.
289
290If a specific suppression mechanism is not available for a certain warning, or
291its use is not desired for some reason, :program:`clang-tidy` has a generic
292mechanism to suppress diagnostics using ``NOLINT`` or ``NOLINTNEXTLINE``
293comments.
294
295The ``NOLINT`` comment instructs :program:`clang-tidy` to ignore warnings on the
296*same line* (it doesn't apply to a function, a block of code or any other
297language construct, it applies to the line of code it is on). If introducing the
298comment in the same line would change the formatting in undesired way, the
299``NOLINTNEXTLINE`` comment allows to suppress clang-tidy warnings on the *next
300line*.
301
302Both comments can be followed by an optional list of check names in parentheses
303(see below for the formal syntax).
304
305For example:
306
307.. code-block:: c++
308
309  class Foo {
310    // Suppress all the diagnostics for the line
311    Foo(int param); // NOLINT
312
313    // Consider explaining the motivation to suppress the warning.
314    Foo(char param); // NOLINT: Allow implicit conversion from `char`, because <some valid reason>.
315
316    // Silence only the specified checks for the line
317    Foo(double param); // NOLINT(google-explicit-constructor, google-runtime-int)
318
319    // Silence only the specified diagnostics for the next line
320    // NOLINTNEXTLINE(google-explicit-constructor, google-runtime-int)
321    Foo(bool param);
322  };
323
324The formal syntax of ``NOLINT``/``NOLINTNEXTLINE`` is the following:
325
326.. parsed-literal::
327
328  lint-comment:
329    lint-command
330    lint-command lint-args
331
332  lint-args:
333    **(** check-name-list **)**
334
335  check-name-list:
336    *check-name*
337    check-name-list **,** *check-name*
338
339  lint-command:
340    **NOLINT**
341    **NOLINTNEXTLINE**
342
343Note that whitespaces between ``NOLINT``/``NOLINTNEXTLINE`` and the opening
344parenthesis are not allowed (in this case the comment will be treated just as
345``NOLINT``/``NOLINTNEXTLINE``), whereas in check names list (inside the
346parenthesis) whitespaces can be used and will be ignored.
347
348.. _LibTooling: https://clang.llvm.org/docs/LibTooling.html
349.. _How To Setup Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
350