[clang-tools-extra] [clang-tidy] Do not warn on const variables in misc-use-internal-linkage (PR #97969)

Carlos Galvez via cfe-commits cfe-commits at lists.llvm.org
Sun Jul 7 12:13:28 PDT 2024


https://github.com/carlosgalvezp created https://github.com/llvm/llvm-project/pull/97969

Since in C++ they already have implicit internal linkage.

Fixes #97947

>From 07bd62f97d203bbdb865cd4b1e14cef3ead70c80 Mon Sep 17 00:00:00 2001
From: Carlos Galvez <carlosgalvezp at gmail.com>
Date: Sun, 7 Jul 2024 21:11:54 +0200
Subject: [PATCH] [clang-tidy] Do not warn on const variables in
 misc-use-internal-linkage

Since in C++ they already have implicit internal linkage.

Fixes #97947
---
 .../clang-tidy/misc/UseInternalLinkageCheck.cpp             | 6 ++++++
 .../clang-tidy/checkers/misc/use-internal-linkage-var.cpp   | 3 +++
 2 files changed, 9 insertions(+)

diff --git a/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp b/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
index 44ccc2bc906a5..c086e7721e02b 100644
--- a/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
@@ -121,6 +121,12 @@ void UseInternalLinkageCheck::check(const MatchFinder::MatchResult &Result) {
     return;
   }
   if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("var")) {
+    // In C++, const variables at file scope have implicit internal linkage,
+    // so we should not warn there. This is not the case in C.
+    // https://eel.is/c++draft/diff#basic-3
+    if (getLangOpts().CPlusPlus && VD->getType().isConstQualified())
+      return;
+
     DiagnosticBuilder DB = diag(VD->getLocation(), Message) << "variable" << VD;
     SourceLocation FixLoc = VD->getTypeSpecStartLoc();
     if (FixLoc.isInvalid() || FixLoc.isMacroID())
diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-var.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-var.cpp
index 01b8d28e61230..6777ce4bb0265 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-var.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-var.cpp
@@ -42,3 +42,6 @@ int global_in_extern_c_1;
 }
 
 extern "C" int global_in_extern_c_2;
+
+const int const_global = 123;
+constexpr int constexpr_global = 123;



More information about the cfe-commits mailing list