On 30 May 2018 at 18:12, Jonathan Wakely <jwakely....@gmail.com> wrote:
> On 30 May 2018 at 11:40, Prathamesh Kulkarni wrote:
>> gcc with -Wmain warns for local variables named main.
>>
>> int foo()
>> {
>>   int main = 0;
>>   return main;
>> }
>>
>> a.c: In function ‘foo’:
>> a.c:3:7: warning: ‘main’ is usually a function [-Wmain]
>>    int main = 1;
>>        ^~~~
>>
>> Is this intended ? I assumed that the warning's intent was for
>> diagnosing variable named main having only external linkage.
>
> It was added more than 20 years ago by https://gcc.gnu.org/r13517 and
> looks like it has always worked as it does now, without considering
> linkage.
>
> Only warning for entities with external linkage seems reasonable to
> me, but that would be for the C front-end or diagnostics maintainers
> to decide.
Thanks for the suggestions. I have attached (untested) patch that warns
for Wmain if TREE_PUBLIC (decl) is true.
Does it look OK ?

Thanks,
Prathamesh
2018-05-30  Prathamesh Kulkarni  <prathamesh.kulka...@linaro.org>

        * c/c-decl.c (start_decl): Add check TREE_PUBLIC (decl) for -Wmain.

testsuite/
        * gcc.dg/wmain.c: New.

diff --git a/gcc/c/c-decl.c b/gcc/c/c-decl.c
index 3c4b18edf56..c5311741629 100644
--- a/gcc/c/c-decl.c
+++ b/gcc/c/c-decl.c
@@ -4700,7 +4700,8 @@ start_decl (struct c_declarator *declarator, struct 
c_declspecs *declspecs,
   if (expr)
     add_stmt (fold_convert (void_type_node, expr));
 
-  if (TREE_CODE (decl) != FUNCTION_DECL && MAIN_NAME_P (DECL_NAME (decl)))
+  if (TREE_CODE (decl) != FUNCTION_DECL && MAIN_NAME_P (DECL_NAME (decl))
+      && TREE_PUBLIC (decl))
     warning (OPT_Wmain, "%q+D is usually a function", decl);
 
   if (initialized)
diff --git a/gcc/testsuite/gcc.dg/wmain.c b/gcc/testsuite/gcc.dg/wmain.c
new file mode 100644
index 00000000000..06fc26fd398
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/wmain.c
@@ -0,0 +1,10 @@
+/* { dg-do compile } */
+/* { dg-options "-Wall" } */
+
+int main; /* { dg-warning "'main' is usually a function" } */
+
+int foo()
+{
+  int main = 1; /* { dg-bogus "'main' is usually a function" } */
+  return main;
+}

Reply via email to