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

Richard Smith richard at metafoo.co.uk
Thu Jul 30 14:00:02 PDT 2015


rsmith added inline comments.

================
Comment at: lib/Sema/SemaDecl.cpp:6110
@@ +6109,3 @@
+  // A program that declares a variable main at global scope is ill-formed.
+  if (getLangOpts().CPlusPlus && Name.getAsString() == "main" &&
+      NewVD->isFileVarDecl()) {
----------------
This check should not apply in `-ffreestanding` mode.

================
Comment at: lib/Sema/SemaDecl.cpp:6110
@@ +6109,3 @@
+  // A program that declares a variable main at global scope is ill-formed.
+  if (getLangOpts().CPlusPlus && Name.getAsString() == "main" &&
+      NewVD->isFileVarDecl()) {
----------------
rsmith wrote:
> This check should not apply in `-ffreestanding` mode.
`getAsString` is not the best thing to use here; it produces a human-readable string (for diagnostics etc). Instead, check `Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main")`.

================
Comment at: lib/Sema/SemaDecl.cpp:6110
@@ +6109,3 @@
+  // A program that declares a variable main at global scope is ill-formed.
+  if (getLangOpts().CPlusPlus && Name.getAsString() == "main" &&
+      NewVD->isFileVarDecl()) {
----------------
rsmith wrote:
> rsmith wrote:
> > This check should not apply in `-ffreestanding` mode.
> `getAsString` is not the best thing to use here; it produces a human-readable string (for diagnostics etc). Instead, check `Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main")`.
In C, an external-linkage variable named `main` results in undefined behavior (because the behavior is undefined if there is no external-linkage function named `main`, and also if there is both a function and a variable named `main`), so we can diagnose that case too.

================
Comment at: test/CXX/basic/basic.start/basic.start.main/p3.cpp:5-8
@@ +4,5 @@
+
+int f () {
+  int main; // OK
+  (void)main;
+}
----------------
Maybe also test:

 * an internal-linkage global variable named `main` (ill-formed in C++, OK in C)
 * a function parameter named `main` (OK)
 * a static data member named `main` (OK, even if defined in TU scope)
 * a variable template named `main` (it looks like this is ill-formed, no diagnostic required, if the variable template has external linkage, and otherwise OK)
 * a variable named `main` within a namespace (OK)
 * a function-scope `extern` variable named `main` (ill-formed)
 * a function-scope `static` variable named `main` (OK)


http://reviews.llvm.org/D11658







More information about the cfe-commits mailing list