[PATCH] D11658: [Sema] main can't be declared as global variable

Richard Smith via cfe-commits cfe-commits at lists.llvm.org
Mon Aug 10 17:18:20 PDT 2015


rsmith added a comment.

Maybe you could refactor the check to something like:

  if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main")
      NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
      !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
    if (getLangOpts().CPlusPlus)
      Diag1;
    else if (NewVD->hasExternalFormalLinkage())
      Diag2;
  }


================
Comment at: include/clang/Basic/DiagnosticSemaKinds.td:514
@@ +513,3 @@
+def err_main_global_variable : Error<"main can't be declared as global variable">;
+def warn_main_redefined : Warning<"external-linkage variable named 'main' has "
+    "undefined behavior">, InGroup<Main>;
----------------
Hyphenating 'external linkage' is unusual; how about 'variable named 'main' with external linkage has undefined behavior'?

================
Comment at: lib/Sema/SemaDecl.cpp:6113
@@ +6112,3 @@
+    // A program that declares a variable main at global scope is ill-formed.
+    if (getLangOpts().CPlusPlus && !getLangOpts().Freestanding &&
+            NewVD->hasGlobalStorage() && !NewVD->isStaticLocal() &&
----------------
The freestanding check should apply in C too.

================
Comment at: lib/Sema/SemaDecl.cpp:6114-6116
@@ +6113,5 @@
+    if (getLangOpts().CPlusPlus && !getLangOpts().Freestanding &&
+            NewVD->hasGlobalStorage() && !NewVD->isStaticLocal() &&
+            !NewVD->isStaticDataMember() && !NewVD->getDescribedVarTemplate() &&
+            NewVD->getDeclContext()->isTranslationUnit())
+          Diag(D.getLocStart(), diag::err_main_global_variable);
----------------
The only checks you need here are: 1) DeclContext's redecl context is the translation unit, and 2) NewVD is not a variable template. All the other checks are implied by the DC check. I'd suggest factoring these out into the main check.

================
Comment at: lib/Sema/SemaDecl.cpp:6116
@@ +6115,3 @@
+            !NewVD->isStaticDataMember() && !NewVD->getDescribedVarTemplate() &&
+            NewVD->getDeclContext()->isTranslationUnit())
+          Diag(D.getLocStart(), diag::err_main_global_variable);
----------------
You need to check `NewVD->getDeclContext()->getRedeclContext()`, in case there are `LinkageSpecDecl`s surrounding the variable (`extern "C++" int main;`).

================
Comment at: lib/Sema/SemaDecl.cpp:6121
@@ +6120,3 @@
+    // behavior.
+    if (!getLangOpts().CPlusPlus && NewVD->isExternC())
+      Diag(D.getLocStart(), diag::warn_main_redefined);
----------------
It's weird to ask `isExternC` from C. Use `hasExternalFormalLinkage` instead.


http://reviews.llvm.org/D11658





More information about the cfe-commits mailing list