65

I'm trying to set up clang-tidy for a project. I'd like to be able to have clean output, and encourage the use of -fix mode where possible. However, there are individual cases where an exception is needed.

Much as it is possible to use

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
// Code that is being specially exempted
#pragma clang diagnostic pop

for the equivalent case where one wants to locally disable a compiler warning, is it possible to do something similar from clang-tidy?

I have tried

#pragma clang diagnostic push
#pragma clang diagnostic ignored "readability-identifier-naming"
// Code that is being specially exempted
#pragma clang diagnostic pop

and also with clang replaced with clang-tidy. Unfortunately when using clang as the pragma target and compiling with regular clang, I get the compilation warning

warning: pragma diagnostic expected option name (e.g. "-Wundef") [-Wunknown-pragmas]

and

warning: unknown pragma ignored [clang-diagnostic-unknown-pragmas]

when compiling if I use clang-tidy in place of clang. Neither make an impact on what clang-tidy itself outputs when run over the source.

This is with clang and clang-tidy 3.8 on x86_64 Linux.

valiano
  • 16,433
  • 7
  • 64
  • 79
Rich L
  • 1,905
  • 2
  • 19
  • 30

2 Answers2

97

Just add a comment containing the string NOLINT anywhere on the line you want clang-tidy to ignore. For example:

badcode;  // NOLINT

// NOLINTNEXTLINE
badcode;

// NOLINTBEGIN
badcode;
badcode;
// NOLINTEND

badcode; // NOLINT(cert-err-58-cpp)

See the documentation here.

Anton Kesy
  • 119
  • 7
Niall Douglas
  • 9,212
  • 2
  • 44
  • 54
  • 3
    And indeed, it seems that opting out of specific checks by (putting-them, in-parentheses) after the // NOLINT is now a feature that was added some time around December 2017. – Rich L Sep 04 '18 at 16:40
  • 7
    To provide an example for @RichL's good hint: `badcode; // NOLINT(cert-err58-cpp)`. This will disable only "cert-err58-cpp" warning and only for this single line (e.g. "cert-err111-cpp" could still be thrown). Make sure there is no white space between NOLINT and (. – Semjon Mössinger Oct 22 '18 at 14:46
11

And since LLVM 14.0.0, you can also use:

// NOLINTBEGIN(cert-err58-cpp)
multiple lines of code;
// NOLINTEND(cert-err58-cpp)
Michael Walton
  • 141
  • 1
  • 6