diff --git a/clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp b/clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp --- a/clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/UseAnonymousNamespaceCheck.cpp @@ -39,6 +39,11 @@ template void UseAnonymousNamespaceCheck::processMatch(const T *MatchedDecl) { + // Enforce anonymous namespaces only in source files, not headers + const SourceManager &SM = MatchedDecl->getASTContext().getSourceManager(); + if (!SM.isWrittenInMainFile(MatchedDecl->getLocation())) + return; + StringRef Type = llvm::isa(MatchedDecl) ? "variable" : "function"; if (isInAnonymousNamespace(MatchedDecl)) diag(MatchedDecl->getLocation(), "%0 %1 declared 'static' in " @@ -54,7 +59,8 @@ Finder->addMatcher( functionDecl(isStatic(), unless(isMemberFunction())).bind("func"), this); Finder->addMatcher( - varDecl(isStatic(), unless(anyOf(isStaticLocal(), isStaticDataMember()))) + varDecl(isStatic(), unless(anyOf(isStaticLocal(), isStaticDataMember(), + hasType(isConstQualified())))) .bind("var"), this); } diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h b/clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h new file mode 100644 --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/Inputs/use-anonymous-namespace.h @@ -0,0 +1,3 @@ +// Should not warn here, require anonymous namespaces only in source files +static int gv{123}; +static void gf(){} diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp --- a/clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/use-anonymous-namespace.cpp @@ -1,4 +1,5 @@ -// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t +// RUN: %check_clang_tidy %s misc-use-anonymous-namespace %t -- -header-filter=.* -- -I%S/Inputs +#include "use-anonymous-namespace.h" static void f1(); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function 'f1' declared 'static', move to anonymous namespace instead [misc-use-anonymous-namespace] @@ -48,12 +49,16 @@ // OK struct Foo { - static void f(); - static int x; + static void f8(); + static int v8; }; // OK void foo() { - static int x; + static int v9; } + +// OK +static const int v10{123}; +static constexpr int v11{123};