diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidNonConstGlobalVariablesCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidNonConstGlobalVariablesCheck.cpp --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidNonConstGlobalVariablesCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidNonConstGlobalVariablesCheck.cpp @@ -17,11 +17,15 @@ namespace tidy { namespace cppcoreguidelines { +namespace { +AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); } +} // namespace + void AvoidNonConstGlobalVariablesCheck::registerMatchers(MatchFinder *Finder) { auto GlobalVariable = varDecl( hasGlobalStorage(), unless(anyOf( - isConstexpr(), hasType(isConstQualified()), + isLocalVarDecl(), isConstexpr(), hasType(isConstQualified()), hasType(referenceType())))); // References can't be changed, only the // data they reference can be changed. @@ -45,11 +49,15 @@ if (const auto *Variable = Result.Nodes.getNodeAs("non-const_variable")) { - diag(Variable->getLocation(), "variable %0 is non-const and globally " - "accessible, consider making it const") - << Variable; // FIXME: Add fix-it hint to Variable - // Don't return early, a non-const variable may also be a pointer or - // reference to non-const data. + // To avoid warning about local variables with global storage, like static + // variables in a function. + if (!Variable->isLocalVarDecl()) { + diag(Variable->getLocation(), "variable %0 is non-const and globally " + "accessible, consider making it const") + << Variable; // FIXME: Add fix-it hint to Variable + // Don't return early, a non-const variable may also be a pointer or + // reference to non-const data. + } } if (const auto *VD = diff --git a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-avoid-non-const-global-variables.cpp b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-avoid-non-const-global-variables.cpp --- a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-avoid-non-const-global-variables.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-avoid-non-const-global-variables.cpp @@ -231,7 +231,8 @@ // CHECKING AGAINST FALSE POSITIVES INSIDE FUNCTION SCOPE ///////////////////// int main() { for (int i = 0; i < 3; ++i) { + static int staticNonConstLoopVariable = 42; int nonConstLoopVariable = 42; - nonConstInt = nonConstLoopVariable + i; + nonConstInt = nonConstLoopVariable + i + staticNonConstLoopVariable; } }