On 09/12/2020 10:25, webmaster wrote:
> Hello,I'm wondering why GCC does not throw any warning when a module global 
> variable is set (write) but never used (read).Is this behavior wanted? Does 
> it makes sense to add such warning?Greets
> 

How do you expect the compiler to know if the variable is never read?

If it has file linkage (it is declared "static") and its address is not
taken and exported out of the translation unit, then the compiler knows
all about it - and could warn about it.  If it has external linkage
(declared at file scope without "static", or with "extern") or its
address is passed out of the translation unit, then the compiler has no
way to tell how it might be used in other translation units.


If you write:

static int xx;
void foo(void) {
        xx = 2;
}

then gcc will eliminate the variable "xx" entirely, as it is never used.
 The function "foo" is compiled to a single "return".  But no
"unused-but-set-variable" warning is emitted - and clearly the compiler
knows that the variable is set but not used.  (You get the warning if
the static variable is local to the function.)

I'd say that it makes sense to have such a warning as a natural
enhancement to the existing "-Wunused-but-set-variable" warning.  But I
can't say if it is a simple matter or not - sometimes these things are
surprisingly difficult to implement depending on the order of passes in
the compiler.  Then it becomes a trade-off of the utility of such a
warning against the effort needed to implement it.


Reply via email to