From b2df6a41f4d626eec3a9de7cbca7b23a28f7b8b7 Mon Sep 17 00:00:00 2001 From: Reid Kleckner Date: Thu, 18 Aug 2016 18:45:07 +0000 Subject: [PATCH] [MS] Silence -Wextern-init on const selectany variables In C, 'extern' is typically used to avoid tentative definitions when declaring variables in headers, but adding an intializer makes it a defintion. This is somewhat confusing, so GCC and Clang both warn on it. In C++, 'extern' is often used to give implictly static 'const' variables external linkage, so don't warn in that case. If selectany is present, this might be header code intended for C and C++ inclusion, so apply the C++ rules. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@279116 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/Sema/SemaDecl.cpp | 13 ++++++++++--- test/Sema/attr-selectany.c | 8 ++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 test/Sema/attr-selectany.c diff --git a/lib/Sema/SemaDecl.cpp b/lib/Sema/SemaDecl.cpp index 55b044d1c5..42f8dea6f6 100644 --- a/lib/Sema/SemaDecl.cpp +++ b/lib/Sema/SemaDecl.cpp @@ -9938,10 +9938,17 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, VDecl->setInvalidDecl(); } } else if (VDecl->isFileVarDecl()) { + // In C, extern is typically used to avoid tentative definitions when + // declaring variables in headers, but adding an intializer makes it a + // defintion. This is somewhat confusing, so GCC and Clang both warn on it. + // In C++, extern is often used to give implictly static const variables + // external linkage, so don't warn in that case. If selectany is present, + // this might be header code intended for C and C++ inclusion, so apply the + // C++ rules. if (VDecl->getStorageClass() == SC_Extern && - (!getLangOpts().CPlusPlus || - !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || - VDecl->isExternC())) && + ((!getLangOpts().CPlusPlus && !VDecl->hasAttr()) || + !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && + !(getLangOpts().CPlusPlus && VDecl->isExternC()) && !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) Diag(VDecl->getLocation(), diag::warn_extern_init); diff --git a/test/Sema/attr-selectany.c b/test/Sema/attr-selectany.c new file mode 100644 index 0000000000..01cca7d7cf --- /dev/null +++ b/test/Sema/attr-selectany.c @@ -0,0 +1,8 @@ +// RUN: %clang_cc1 -fms-compatibility -fms-extensions -verify %s + +extern __declspec(selectany) const int x1 = 1; // no warning, const means we need extern in C++ + +// Should we really warn on this? +extern __declspec(selectany) int x2 = 1; // expected-warning {{'extern' variable has an initializer}} + +__declspec(selectany) void foo() { } // expected-error{{'selectany' can only be applied to data items with external linkage}} -- 2.50.1