Bug 28901 - -Wunused-variable ignores unused const initialised variables
Summary: -Wunused-variable ignores unused const initialised variables
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 4.1.1
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
: 20562 59849 (view as bug list)
Depends on:
Blocks:
 
Reported: 2006-08-30 11:55 UTC by Mikael Pettersson
Modified: 2016-11-08 15:59 UTC (History)
17 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2014-08-08 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Mikael Pettersson 2006-08-30 11:55:25 UTC
gcc -Wunused-variable -c test.c, where test.c contains the
following code, fails to warn that variable a is unused:
--begin-test.c-
static const int a = 27;
static const int b = 42;
const int *f(void) { return &b; }
--end-test.c--
However, gcc -Wunused-variable -c -Dconst= test.c does 
produce the warning I wanted:
test.c:1: warning: 'a' defined but not used

The problem is that for some reason, -Wunused-variable ignores
const variables, and there doesn't seem to be any alternative
warning option or variable attribute to request unused warnings
for const variables.

In the application where this was observed, there is a large number
of initialised const arrays-of-structs encoding final-state
information for a state transition engine. Other const variables
and functions encode the fairly complex transition rules. A copy-paste
error in the transition rules led to some final states not being
reachable, i.e., there were no references to those variables, but
-Wunused-variable (implied by -Wall) failed to notice that.
Comment 1 Andrew Pinski 2006-09-19 05:13:45 UTC
This is not a bug but a feature.  The reason is that const int usually shows up in header files and usually are normally unused.
Comment 2 Andrew Pinski 2014-01-16 23:51:58 UTC
*** Bug 59849 has been marked as a duplicate of this bug. ***
Comment 3 Andrew Pinski 2014-01-16 23:55:48 UTC
From the code:
       /* We don't warn about "static const" variables because the
	  "rcs_id" idiom uses that construction.  */
Comment 4 H.J. Lu 2014-01-17 00:26:51 UTC
(In reply to Andrew Pinski from comment #3)
> From the code:
>        /* We don't warn about "static const" variables because the
> 	  "rcs_id" idiom uses that construction.  */

That is not a good reason not to warn:

[hjl@gnu-mic-2 gcc]$ cat /tmp/w.c
static const int foo[0x1000];
[hjl@gnu-mic-2 gcc]$ gcc  -Wall -S /tmp/w.c
[hjl@gnu-mic-2 gcc]$ cat w.s
	.file	"w.c"
	.local	foo
	.comm	foo,16384,32
	.ident	"GCC: (GNU) 4.8.2 20140115 (Red Hat 4.8.2-11)"
	.section	.note.GNU-stack,"",@progbits
[hjl@gnu-mic-2 gcc]$ 

If we want to avoid rcs_id warning, we can check it explicitly and
not to warn it.
Comment 5 Tom Tromey 2014-02-11 17:39:52 UTC
I would like this bug to be reopened.

I've read through this bug and various dups,
and it seems that there are two rationales given
for skipping the warning for const statics:

1. rcs_id.  It seems to me that this case could
   be handled by __attribute__((used)).

2. "static const"s appearing in system headers.
   It seems to me that this could be handled by
   the usual in_system_header_at check.

This warning would have caught a couple of previously
unnoticed bugs in gdb: https://sourceware.org/ml/gdb-patches/2014-02/msg00342.html
Comment 6 Tom Tromey 2014-08-08 14:18:27 UTC
I finally decided I would just reopen it.
If this is in error someone can easily close it again.
However please take note of the arguments in favor of
this being a bug in comment #5.  Thanks.
Comment 7 petschy 2014-10-22 18:47:09 UTC
For backward compatibility, wouldn't it be better to add a new flag, -Wunused-static-const-variable, instead of changing the behaviour of -Wunused-variable?
Comment 8 Mark Wielaard 2015-09-11 22:15:22 UTC
Submitted a patch:
https://gcc.gnu.org/ml/gcc-patches/2015-09/msg00847.html
Comment 9 Mark Wielaard 2015-09-14 09:50:19 UTC
Author: mark
Date: Mon Sep 14 09:49:47 2015
New Revision: 227742

URL: https://gcc.gnu.org/viewcvs?rev=227742&root=gcc&view=rev
Log:
PR28901 -Wunused-variable ignores unused const initialised variables in C

12 years ago it was decided that -Wunused-variable shouldn't warn about
static const variables because some code used const static char rcsid[]
strings which were never used but wanted in the code anyway. But as the
bug points out this hides some real bugs. These days the usage of rcsids
is not very popular anymore. So this patch changes the default to warn
about unused static const variables in C with -Wunused-variable. And it
adds a new option -Wno-unused-const-variable to turn this warning off.
For C++ this new warning is off by default, since const variables can be
used as #defines in C++. New testcases for the new defaults in C and C++
are included testing the new warning and suppressing it with an unused
attribute or using -Wno-unused-const-variable.

gcc/ChangeLog

       PR c/28901
       * toplev.c (check_global_declaration): Check and use
       warn_unused_const_variable.
       * doc/invoke.texi (Warning Options): Add -Wunused-const-variable.
       (-Wunused-variable): Remove non-constant. For C implies
       -Wunused-const-variable.
       (-Wunused-const-variable): New.

gcc/c-family/ChangeLog

       PR c/28901
       * c.opt (Wunused-variable): Option from common.opt.
       (Wunused-const-variable): New option.

gcc/cp/ChangeLog

       PR c/28901
       * cp-objcp-common.c (cxx_warn_unused_global_decl): Remove hard-coded
       VAR_P TREE_READONLY override.

gcc/testsuite/ChangeLog

       PR c/28901
       * g++.dg/warn/unused-variable-1.C: New test.
       * g++.dg/warn/unused-variable-2.C: Likewise.
       * gcc.dg/unused-4.c: Adjust warning for static const.
       * gcc.dg/unused-variable-1.c: New test.
       * gcc.dg/unused-variable-2.c: Likewise.

Added:
    trunk/gcc/testsuite/g++.dg/warn/unused-variable-1.C
    trunk/gcc/testsuite/g++.dg/warn/unused-variable-2.C
    trunk/gcc/testsuite/gcc.dg/unused-variable-1.c
    trunk/gcc/testsuite/gcc.dg/unused-variable-2.c
Modified:
    trunk/gcc/ChangeLog
    trunk/gcc/c-family/ChangeLog
    trunk/gcc/c-family/c.opt
    trunk/gcc/cp/ChangeLog
    trunk/gcc/cp/cp-objcp-common.c
    trunk/gcc/doc/invoke.texi
    trunk/gcc/testsuite/ChangeLog
    trunk/gcc/testsuite/gcc.dg/unused-4.c
    trunk/gcc/toplev.c
Comment 10 Paul Eggert 2015-09-18 23:05:59 UTC
This topic came up on the libc-alpha mailing list.  The proposed change would break compilation of tzcode, which has a private header that defines static constants not all of which are used in every file that includes the header.

In tzcode the problem can be worked around by using a #define rather than a static constant, but many C programmers nowadays prefer avoiding #define when possible, and static constants let you do that in many cases. (An enum wouldn't work for the tzcode case, as the values might be outside int range.)  Also, in many environments macros are invisible to the debugger but static constants are visible, so the static constants are nicer for people debugging their code.

This reminds me of when gcc -Wmissing-declarations used to diagnose every C99-style inline function in an include file (GCC bug 63877). The warning was put in and tested, but the tests used only old-fashioned C programming styles, and the warning caused real problems by people using a more modern C style.

It'd be fine to add an option to enable the new warning, but please don't enable them merely because -Wall or -Wunused-variable is specified.
Comment 11 Manuel López-Ibáñez 2015-09-18 23:43:09 UTC
(In reply to Paul Eggert from comment #10)
> In tzcode the problem can be worked around by using a #define rather than a
> static constant, but many C programmers nowadays prefer avoiding #define

__attribute__((unused)) should silence the warning when inappropriate.

Another alternative is to only warn if the variable is defined in the main file (MAIN_FILE_P) as opposed to an included file.

> It'd be fine to add an option to enable the new warning, but please don't
> enable them merely because -Wall or -Wunused-variable is specified.

The problem with not adding options to at least -Wall or -Wextra is that they will be almost never used, even if they are only noisy for a small percentage of cases, which just may need a bit of fine-tuning or accepting some false negatives to avoid some false positives. 

We have a lot of options that are not in Wall or Wextra just because they were noisy in some particular cases, and it was easier to move them out of the way than to fix them. Since they are not used, there is small motivation to ever fix them.
Comment 12 Paul Eggert 2015-09-19 04:51:43 UTC
(In reply to Manuel López-Ibáñez from comment #11)

> Another alternative is to only warn if the variable is defined in the main
> file (MAIN_FILE_P) as opposed to an included file.

Thanks, this is a reasonable suggestion; it would fix the cry-wolf problem for tzcode, which is what prompted me to object to the original proposal.

The alternative of littering the code with many instances of __attribute__ ((unused)) (or is it __attribute ((used)? I can never remember) is less appealing.
Comment 13 Manuel López-Ibáñez 2015-09-19 09:27:22 UTC
(In reply to Paul Eggert from comment #12)
> (In reply to Manuel López-Ibáñez from comment #11)
> 
> > Another alternative is to only warn if the variable is defined in the main
> > file (MAIN_FILE_P) as opposed to an included file.
> 
> Thanks, this is a reasonable suggestion; it would fix the cry-wolf problem
> for tzcode, which is what prompted me to object to the original proposal.
> 
> The alternative of littering the code with many instances of __attribute__
> ((unused)) (or is it __attribute ((used)? I can never remember) is less
> appealing.

https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#index-g_t_0040code_007bunused_007d-variable-attribute-3382

unused
    This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC does not produce a warning for this variable.

used
    This attribute, attached to a variable with static storage, means that the variable must be emitted even if it appears that the variable is not referenced.

(I think "used" should also silence the warning).
Comment 14 Andi Kleen 2015-11-30 04:50:53 UTC
I'm building a current Linux kernel with allyesconfig, and this new warning causes
1383(!) new warnings in the build.

I think this should be revisited and the warning be turned off again.
Comment 15 Mark Wielaard 2015-11-30 08:16:54 UTC
(In reply to Andi Kleen from comment #14)
> I'm building a current Linux kernel with allyesconfig, and this new warning
> causes
> 1383(!) new warnings in the build.
> 
> I think this should be revisited and the warning be turned off again.

Could you post some examples?
Are they in your opinion all false positives?
Or is there a specific pattern to the ones you think are falsely flagged?
Note that you can always just specify -Wno-unused-const-variable if they are real warnings, but you wish to ignore them.
Comment 16 Markus Trippelsdorf 2015-11-30 08:38:05 UTC
I looked at some of the kernel warnings and they were legitimate.
The embedded guys, who care much about binary size, would benefit most
if these issues were fixed.
Comment 17 Andi Kleen 2015-11-30 08:55:41 UTC
There were a few false or useless ones (e.g. related to macros and specific build configs).  I didn't look through them all, but various were semi legitimate, but also very minor (small) so fixing it won't help much. I think one or two of the ones I looked at may have been real bugs.

I still think the warning should not be in -Wall. thousand+ warnings in real projects is just not acceptable.
Comment 18 Markus Trippelsdorf 2015-11-30 09:03:32 UTC
Here is an example:
...
static const struct pt_regs_offset x86_32_regoffset_table[] = {
        REG_OFFSET_NAME_32("%ax",       eax),
        REG_OFFSET_NAME_32("%cx",       ecx),
        REG_OFFSET_NAME_32("%dx",       edx),
        REG_OFFSET_NAME_32("%bx",       ebx),
        REG_OFFSET_NAME_32("$stack",    esp),   /* Stack address instead of %sp */
        REG_OFFSET_NAME_32("%bp",       ebp),
        REG_OFFSET_NAME_32("%si",       esi),
        REG_OFFSET_NAME_32("%di",       edi),
        REG_OFFSET_END,
};

static const struct pt_regs_offset x86_64_regoffset_table[] = {
        REG_OFFSET_NAME_64("%ax",       rax),
        REG_OFFSET_NAME_64("%dx",       rdx),
        REG_OFFSET_NAME_64("%cx",       rcx),
        REG_OFFSET_NAME_64("%bx",       rbx),
        REG_OFFSET_NAME_64("%si",       rsi),
        REG_OFFSET_NAME_64("%di",       rdi),
        REG_OFFSET_NAME_64("%bp",       rbp),
        REG_OFFSET_NAME_64("%sp",       rsp),
        REG_OFFSET_NAME_64("%r8",       r8),
        REG_OFFSET_NAME_64("%r9",       r9),
        REG_OFFSET_NAME_64("%r10",      r10),
        REG_OFFSET_NAME_64("%r11",      r11),
        REG_OFFSET_NAME_64("%r12",      r12),
        REG_OFFSET_NAME_64("%r13",      r13),
        REG_OFFSET_NAME_64("%r14",      r14),
        REG_OFFSET_NAME_64("%r15",      r15),
        REG_OFFSET_END,
};

/* TODO: switching by dwarf address size */
#ifdef __x86_64__
#define regoffset_table x86_64_regoffset_table
#else
#define regoffset_table x86_32_regoffset_table
#endif
...
//use regoffset_table
Comment 19 Chen Gang 2016-01-26 13:59:10 UTC
I build linux kernel with allyesconfig under x86_64 for linux-next tree 20160122. I can find some related cases for BUG28901 (but they are not quite much), one case is below:

  CC      drivers/acpi/sbshc.o
In file included from drivers/acpi/sbshc.c:17:0:
drivers/acpi/sbshc.h:17:17: warning: ‘SMBUS_PEC’ defined but not used [-Wunused-const-variable]
 static const u8 SMBUS_PEC = 0x80;
                 ^~~~~~~~~

For me, I dislike -Wno-unused-const-variable option, the reason is "when C programmers use static const int variable, in most cases, they want to use them instead of #define".

So for me, -Wunused-variable need skip static const int variable warning. If anyone wants to warn about it, they can add additional option (e.g. -Wunused-const-int-variable) to let C compiler report warning for it.

Thanks.
Comment 20 Chen Gang 2016-01-26 14:03:26 UTC
(In reply to Chen Gang from comment #19)
> I build linux kernel with allyesconfig under x86_64 for linux-next tree
> 20160122. I can find some related cases for BUG28901 (but they are not quite
> much), one case is below:
> 
>   CC      drivers/acpi/sbshc.o
> In file included from drivers/acpi/sbshc.c:17:0:
> drivers/acpi/sbshc.h:17:17: warning: ‘SMBUS_PEC’ defined but not used
> [-Wunused-const-variable]
>  static const u8 SMBUS_PEC = 0x80;
>                  ^~~~~~~~~

Oh, sorry, this case is not suitable, it is -Wunused-const-variable.


But my opinion still like what I said in comment #19.

Thanks.
Comment 21 Mark Wielaard 2016-01-26 16:14:36 UTC
Sorry, I forgot about this bug still being open.

It isn't clear to me whether the issues seen in the kernel sources are
a) just legitimate and should be fixed
   (like comment #16 seem to imply)
b) thousand+ warnings and only a few legitimate warnings
   (as comment #17 seems to imply)
c) not quite much warnings, though some unwanted
   (like comment #19 says)

Although in C a static const is not really like a #define I suspect that there are cases where they are used as such in header files. If that is the major reason for why there are people opposed to the warning then what we could do is hide such (non-)usage of static const variables from header files behind -Wextra and only explicitly warn for static const variable defined (and then not used) in the main file.

diff --git a/gcc/cgraphunit.c b/gcc/cgraphunit.c
index b95c172..acf8fe5 100644
--- a/gcc/cgraphunit.c
+++ b/gcc/cgraphunit.c
@@ -944,7 +944,10 @@ check_global_declaration (symtab_node *snode)
   /* Warn about static fns or vars defined but not used.  */
   if (((warn_unused_function && TREE_CODE (decl) == FUNCTION_DECL)
        || (((warn_unused_variable && ! TREE_READONLY (decl))
-           || (warn_unused_const_variable && TREE_READONLY (decl)))
+           || (warn_unused_const_variable && TREE_READONLY (decl)
+               && (extra_warnings
+                   || filename_cmp (main_input_filename,
+                                    DECL_SOURCE_FILE (decl)) == 0)))
           && TREE_CODE (decl) == VAR_DECL))
       && ! DECL_IN_SYSTEM_HEADER (decl)
       && ! snode->referred_to_p (/*include_self=*/false)
Comment 22 Chen Gang 2016-01-28 22:36:23 UTC
(In reply to Mark Wielaard from comment #21)

[...]

> Although in C a static const is not really like a #define I suspect that
> there are cases where they are used as such in header files. If that is the
> major reason for why there are people opposed to the warning then what we
> could do is hide such (non-)usage of static const variables from header
> files behind -Wextra and only explicitly warn for static const variable
> defined (and then not used) in the main file.
> 

For me, what you said above sounds reasonable. :-)
Comment 23 Josh Triplett 2016-02-15 18:58:28 UTC
(In reply to Mark Wielaard from comment #21)
> Although in C a static const is not really like a #define

Why not?  Many C projects try to avoid the preprocessor as much as possible.

> I suspect that
> there are cases where they are used as such in header files. If that is the
> major reason for why there are people opposed to the warning then what we
> could do is hide such (non-)usage of static const variables from header
> files behind -Wextra and only explicitly warn for static const variable
> defined (and then not used) in the main file.

Please don't attach this to -Wextra; instead, please consider making it a -Wconst-unused-variable=2 or similar.  Otherwise, projects using static const values in header files would get a massive pile of additional warnings, typically all false positives.

In a main file, this makes sense and likely has relatively few false positives; the most common false positive would involve defining something only used in ifdef'd code, and even then tagging it with __attribute__((unused)) (Linux's __maybe_unused) seems correct.

However, in a header file, any use of static const to define constants for a project will almost certainly get this warning, unless every single user of that header file (directly or indirectly) uses every constant (or unless the header itself does).  Silently throwing away the unused constants seems like the right thing to do there.
Comment 24 Josh Triplett 2016-02-15 19:00:37 UTC
Also, even the documentation seems unfortunate: "In C++ this is normally not an error since const variables take the place of #defines in C++."

Why would C code not do this too?  The GCC documentation should not steer people away from this practice in C, or imply that there's something wrong with it.
Comment 25 Mark Wielaard 2016-02-16 21:16:00 UTC
(In reply to Josh Triplett from comment #23)
> (In reply to Mark Wielaard from comment #21)
> > Although in C a static const is not really like a #define
> 
> Why not?  Many C projects try to avoid the preprocessor as much as possible.

The difference is that a static const defines variable storage in C.

> > I suspect that
> > there are cases where they are used as such in header files. If that is the
> > major reason for why there are people opposed to the warning then what we
> > could do is hide such (non-)usage of static const variables from header
> > files behind -Wextra and only explicitly warn for static const variable
> > defined (and then not used) in the main file.
> 
> Please don't attach this to -Wextra; instead, please consider making it a
> -Wconst-unused-variable=2 or similar.  Otherwise, projects using static
> const values in header files would get a massive pile of additional
> warnings, typically all false positives.

Do you mean split it into -Wconst-unused-variable=1 for main compile unit that is part of -Wunused-variable and a -Wconst-unused-variable=2 that is activated by -Wextra?
 
> In a main file, this makes sense and likely has relatively few false
> positives; the most common false positive would involve defining something
> only used in ifdef'd code, and even then tagging it with
> __attribute__((unused)) (Linux's __maybe_unused) seems correct.
> 
> However, in a header file, any use of static const to define constants for a
> project will almost certainly get this warning, unless every single user of
> that header file (directly or indirectly) uses every constant (or unless the
> header itself does).  Silently throwing away the unused constants seems like
> the right thing to do there.

I am trying to find out if there are any false positives, or warnings that people really find annoying and cannot easily fix. If so, it might make sense to split the warning. But at least from the comments in this bug report it is unclear to me. Maybe it is obvious to others. But see comment #21 for the 3 ways to read the comments in this bug report.

What is clear is that there is no consensus. Maybe that is enough reason to do the split anyway. But it would be nice to have some actual examples in actual code that everybody agrees is not OK to warn about.
Comment 26 Panu Matilainen 2016-02-17 09:01:30 UTC
(In reply to Josh Triplett from comment #23)
> Please don't attach this to -Wextra; instead, please consider making it a
> -Wconst-unused-variable=2 or similar.  Otherwise, projects using static
> const values in header files would get a massive pile of additional
> warnings, typically all false positives.
>
> In a main file, this makes sense and likely has relatively few false
> positives; the most common false positive would involve defining something
> only used in ifdef'd code, and even then tagging it with
> __attribute__((unused)) (Linux's __maybe_unused) seems correct.
> 
> However, in a header file, any use of static const to define constants for a
> project will almost certainly get this warning, unless every single user of
> that header file (directly or indirectly) uses every constant (or unless the
> header itself does).  Silently throwing away the unused constants seems like
> the right thing to do there. 

Seconded, +100, amen. 

On main files warning on unused junk is certainly useful but static const is commonly and deliberately used in headers (eg for arrays such as in comment #18) and now produces unhelpful false positives. In case somebody really wants to see the warnings from headers too, something like -Wconst-unused-variable=2 sounds fine but it should not be a default.

Just as a random data point: out of the three projects I've so far compiled with gcc 6 (on fedora rawhide), two have false positives from static const arrays in headers. The other one has them by the dozen.
Comment 27 Manuel López-Ibáñez 2016-02-17 17:28:31 UTC
(In reply to Mark Wielaard from comment #21)
> Although in C a static const is not really like a #define I suspect that
> there are cases where they are used as such in header files. If that is the
> major reason for why there are people opposed to the warning then what we
> could do is hide such (non-)usage of static const variables from header
> files behind -Wextra and only explicitly warn for static const variable
> defined (and then not used) in the main file.

We should not use -Wextra in this way, because after seeing the warning, it is not apparent to the user which option controls it. (That is, the same warning option printed in the output behaves differently when -Wextra is given).

My suggestion is to never warn if declared in a header. If an extra option is desired (whether enabled by -Wextra or explicitly), then it would be better to call it something like Wunused-any-const-variable, because the meaning of numeric values are not apparent (and they do not play nicely with -Werror=).

Note that it is trivial to find all unused static const variables in your headers: Just preprocess the file, remove line info and compile with -Wunused.

> +                   || filename_cmp (main_input_filename,
> +                                    DECL_SOURCE_FILE (decl)) == 0)))

Better use MAIN_FILE_P(DECL_SOURCE_LOCATION (decl))

Whoever wants to see this fixed, should hurry up before GCC 6 closes.
Comment 28 Mark Wielaard 2016-02-21 01:03:32 UTC
(In reply to Panu Matilainen from comment #26)
> On main files warning on unused junk is certainly useful but static const is
> commonly and deliberately used in headers (eg for arrays such as in comment
> #18) and now produces unhelpful false positives.

I don't think the comment #18 was meant to show a false positive, just the opposite. The example is not in an header and seems like a simple bug with misplaced #ifdef/#else statements.

> Just as a random data point: out of the three projects I've so far compiled
> with gcc 6 (on fedora rawhide), two have false positives from static const
> arrays in headers. The other one has them by the dozen.

It would be helpful to make these data points more concrete so we can all easily check the claims that these are not errors, but false positives.
Comment 29 Mark Wielaard 2016-02-21 01:28:56 UTC
(In reply to Manuel López-Ibáñez from comment #27)
> (In reply to Mark Wielaard from comment #21)
> > Although in C a static const is not really like a #define I suspect that
> > there are cases where they are used as such in header files. If that is the
> > major reason for why there are people opposed to the warning then what we
> > could do is hide such (non-)usage of static const variables from header
> > files behind -Wextra and only explicitly warn for static const variable
> > defined (and then not used) in the main file.
> 
> We should not use -Wextra in this way, because after seeing the warning, it
> is not apparent to the user which option controls it. (That is, the same
> warning option printed in the output behaves differently when -Wextra is
> given).

OK, fair point.
 
> My suggestion is to never warn if declared in a header. If an extra option
> is desired (whether enabled by -Wextra or explicitly), then it would be
> better to call it something like Wunused-any-const-variable, because the
> meaning of numeric values are not apparent (and they do not play nicely with
> -Werror=).

I don't like to introduce yet another warning option name, there are several warnings with increasing levels. If we go with enabling higher levels only explicitly it seems fairly clear which level is meant. And I believe they are clearly documented. If this is an issue with -Werror= then lets fix -Werror. There are multiple warnings which have increasing levels.

> Note that it is trivial to find all unused static const variables in your
> headers: Just preprocess the file, remove line info and compile with
> -Wunused.
> 
> > +                   || filename_cmp (main_input_filename,
> > +                                    DECL_SOURCE_FILE (decl)) == 0)))
> 
> Better use MAIN_FILE_P(DECL_SOURCE_LOCATION (decl))

MAIN_FILE_P doesn't take a source location, but a line_map_ordinary, which seems more cumbersome to get at from a decl then the filename to compare against.
Comment 31 Manuel López-Ibáñez 2016-02-21 22:43:31 UTC
(In reply to Mark Wielaard from comment #29)
> > > +                   || filename_cmp (main_input_filename,
> > > +                                    DECL_SOURCE_FILE (decl)) == 0)))
> > 
> > Better use MAIN_FILE_P(DECL_SOURCE_LOCATION (decl))
> 
> MAIN_FILE_P doesn't take a source location, but a line_map_ordinary, which
> seems more cumbersome to get at from a decl then the filename to compare
> against.

Ah, yes, sorry. One needs to lookup the map for the location before being able to use MAIN_FILE_P. I was hoping that there was already a convenient overload or similar function in input.h or line-map.h, but alas, there isn't.

I think it is still worth it to add something like in_main_file_at(location_t), similar to the existing in_system_header_at(), even if you wish to use filename_cmp within it. Somebody else in the future may decide to replace that implementation with something using MAIN_FILE_P, since it is much faster.
Comment 32 Mark Wielaard 2016-02-22 22:42:50 UTC
Author: mark
Date: Mon Feb 22 22:42:19 2016
New Revision: 233616

URL: https://gcc.gnu.org/viewcvs?rev=233616&root=gcc&view=rev
Log:
PR28901 Add two levels for -Wunused-const-variable.

There is some controversy about enabling -Wunused-const-variable for all
unused static const variables because some feel there are too many errors
exposed in header files. Create two levels for -Wunused-const-variable.
One level to only check for unused static const variables in the main
compilation file. Which is enabled by -Wunused-variable. And a second
level that also checks for unused static const variables in included
files. Which must be explicitly enabled.

gcc/ChangeLog

	PR c/28901
	* cgraphunit.c (check_global_declaration): Check level of
	warn_unused_const_variable and main_input_filename.
	* doc/invoke.texi (Warning Options): Add -Wunused-const-variable=.
	(-Wunused-variable): For C implies -Wunused-const-variable=1.
	(-Wunused-const-variable): Explain levels 1 and 2.

gcc/c-family/ChangeLog

	PR c/28901
	* c.opt (Wunused-const-variable): Turn into Alias for...
	(Wunused-const-variable=): New option.

gcc/testsuite/ChangeLog

	PR c/28901
	* gcc.dg/unused-variable-3.c: New test.

Added:
    trunk/gcc/testsuite/gcc.dg/unused-variable-3.c
Modified:
    trunk/gcc/ChangeLog
    trunk/gcc/c-family/ChangeLog
    trunk/gcc/c-family/c.opt
    trunk/gcc/cgraphunit.c
    trunk/gcc/doc/invoke.texi
    trunk/gcc/testsuite/ChangeLog
Comment 33 Andreas Schwab 2016-02-23 09:41:13 UTC
make[3]: Entering directory '/opt/gcc/test/Build/lto-plugin'
/bin/sh ./libtool --tag=CC --tag=disable-static  --mode=compile /opt/gcc/test/Build/./prev-gcc/xgcc -B/opt/gcc/test/Build/./prev-gcc/ -B/usr/aarch64-suse-linux/bin/ -B/usr/aarch64-suse-linux/bin/ -B/usr/aarch64-suse-linux/lib/ -isystem /usr/aarch64-suse-linux/include -isystem /usr/aarch64-suse-linux/sys-include    -DHAVE_CONFIG_H -I. -I../../lto-plugin  -I../../lto-plugin/../include -DHAVE_CONFIG_H  -Wall -g -O2 -gtoggle -c -o lto-plugin.lo ../../lto-plugin/lto-plugin.c
libtool: compile:  /opt/gcc/test/Build/./prev-gcc/xgcc -B/opt/gcc/test/Build/./prev-gcc/ -B/usr/aarch64-suse-linux/bin/ -B/usr/aarch64-suse-linux/bin/ -B/usr/aarch64-suse-linux/lib/ -isystem /usr/aarch64-suse-linux/include -isystem /usr/aarch64-suse-linux/sys-include -DHAVE_CONFIG_H -I. -I../../lto-plugin -I../../lto-plugin/../include -DHAVE_CONFIG_H -Wall -g -O2 -gtoggle -c ../../lto-plugin/lto-plugin.c  -fPIC -DPIC -o .libs/lto-plugin.o
cc1: internal compiler error: Segmentation fault
0xf1a03b crash_signal
        ../../gcc/toplev.c:335
0x17fb3cf filename_cmp
        ../../libiberty/filename_cmp.c:60

(gdb) bt
#0  strcmp () at ../sysdeps/aarch64/strcmp.S:63
#1  0x00000000017fb3d0 in filename_cmp (
    s1=0x1f36b00 "../../lto-plugin/lto-plugin.c", s2=0x0)
    at ../../libiberty/filename_cmp.c:60
#2  0x000000000099a038 in check_global_declaration (snode=0x3ffb5e90480)
    at ../../gcc/cgraphunit.c:947
#3  0x000000000099adb8 in analyze_functions (first_time=true)
    at ../../gcc/cgraphunit.c:1168
#4  0x000000000099f4e8 in symbol_table::finalize_compilation_unit (
    this=0x3ffb59e0000) at ../../gcc/cgraphunit.c:2537
#5  0x0000000000f1a688 in compile_file () at ../../gcc/toplev.c:490
#6  0x0000000000f1da10 in do_compile () at ../../gcc/toplev.c:1988
#7  0x0000000000f1dd74 in toplev::main (this=0x3fffffff038, argc=18, 
    argv=0x3fffffff188) at ../../gcc/toplev.c:2096
#8  0x000000000176d228 in main (argc=18, argv=0x3fffffff188)
    at ../../gcc/main.c:39
Comment 35 Mark Wielaard 2016-02-23 12:19:43 UTC
Note the followup patch needed for PR c/69911
https://gcc.gnu.org/viewcvs?rev=233627&root=gcc&view=rev
Comment 36 Mark Wielaard 2016-02-23 12:20:49 UTC
I believe the warning is perfect now.
If not, please feel free to reopen this issue.
Comment 37 Andrew Pinski 2016-03-13 08:43:09 UTC
Note this change also introduces some warnings when compiling the arm64 kernel:

In file included from arch/arm64/crypto/aes-glue.c:17:0:
include/linux/cpufeature.h:48:33: warning: ‘cpu_feature_match_AES’ defined but not used [-Wunused-const-variable=]
 static struct cpu_feature const cpu_feature_match_ ## x[] = \
                                 ^
arch/arm64/crypto/aes-glue.c:452:1: note: in expansion of macro ‘module_cpu_feature_match’
 module_cpu_feature_match(AES, aes_init);
 ^~~~~~~~~~~~~~~~~~~~~~~~

 
 MODULE_DEVICE_TABLE(cpu, cpu_feature_match_ ## x);              \


This happens when the aes crypto code is compiled in rather than a module.
Comment 38 Martin Sebor 2016-04-15 19:10:17 UTC
*** Bug 20562 has been marked as a duplicate of this bug. ***
Comment 39 Pekka 2016-11-08 15:59:56 UTC
Well this change did now hit me.

We have a code base of thousands of modules for a set of industrial systems. Every now and then we must recompile for new platforms with new versions of things like gcc. And now is one such time.

The code base has been developed over 20 odd years and continues. Nearly every time some backward compatibility is broken it is a big headache for me. Some modules must be updated. Usually gcc warnings are very helpful in this. But now I get thousand of them. I our environment it is absolutely necessary to have version strings in every singe module to be stamped inside the created binary. Every module has it own versions. Modules are normally developed independently (a bit like kernel drivers).

Years ago when 'unused warning' appeared we had this tedious project to add 'const' to every version stamp in every module (there are different version string names for different purposes). I must now figure out what is the best solution.

There must be millions of C-modules out there that are still in current use and have versions or something similar stamped in they binaries.

I see the need for progress but I must say I'm quite annoyed on how lightly in the open source world backward compatibility is broken.