Skip to content

Commit 89265bf

Browse files
committed
Add option to ignore anonymous namespaces in avoid-non-const-global-variables
1 parent 662b130 commit 89265bf

File tree

3 files changed

+118
-47
lines changed

3 files changed

+118
-47
lines changed

clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidNonConstGlobalVariablesCheck.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
//===----------------------------------------------------------------------===//
88

99
#include "AvoidNonConstGlobalVariablesCheck.h"
10-
#include "clang/AST/ASTContext.h"
1110
#include "clang/ASTMatchers/ASTMatchFinder.h"
1211
#include "clang/ASTMatchers/ASTMatchers.h"
1312

@@ -16,9 +15,12 @@ using namespace clang::ast_matchers;
1615
namespace clang::tidy::cppcoreguidelines {
1716

1817
void AvoidNonConstGlobalVariablesCheck::registerMatchers(MatchFinder *Finder) {
18+
auto NamespaceMatcher = Options.get("AllowAnonymousNamespace", false)
19+
? namespaceDecl(unless(isAnonymous()))
20+
: namespaceDecl();
1921
auto GlobalContext =
2022
varDecl(hasGlobalStorage(),
21-
hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl())));
23+
hasDeclContext(anyOf(NamespaceMatcher, translationUnitDecl())));
2224

2325
auto GlobalVariable = varDecl(
2426
GlobalContext,

clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/avoid-non-const-global-variables.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,25 @@ The variables ``a``, ``c``, ``c_ptr1``, ``c_const_ptr`` and ``c_reference``
4141
will all generate warnings since they are either a non-const globally accessible
4242
variable, a pointer or a reference providing global access to non-const data
4343
or both.
44+
45+
Options
46+
-------
47+
48+
.. option:: AllowAnonymousNamespace
49+
50+
When set to `true` (default is `false`), non-const variables in anonymous namespaces will not generate a warning.
51+
52+
Example
53+
^^^^^^^
54+
55+
.. code-block:: c++
56+
57+
namespace {
58+
int counter = 0;
59+
}
60+
61+
int Increment() {
62+
return ++counter;
63+
}
64+
65+
will not generate a warning for `counter` if :option:`AllowAnonymousNamespace` is set to `true`.

0 commit comments

Comments
 (0)