Why gcc gives error of unused variable for local variables but not for global variables?

StackOverflow https://stackoverflow.com/questions/664414

  •  21-08-2019
  •  | 
  •  

Question

I have a question regarding gcc. Why I get an error of unused variable when I define the variable locally in a function but not when the variable is global in a unique file?.

I can understand that it can be use for someone else, but to do that then I need to put the external word right?

Thanks in advance.

Was it helpful?

Solution

If by "global in a unique file", you mean "int x;" outside of any function, the it's not the compilers job to detect that, the variable needs to be available to the linker in case another compilation unit needs it (such as errno).

If you meant "static int x" where it's not made available to the linker, this is probably just a choice made by GCC. I don't believe compilers are required to notify of this and it does no real damage other than wasting a few bytes in your address space.

OTHER TIPS

The compiler has no way of knowing if a global variable is used - it could be used from a compilation unit written in a completely different language, for example.

Because global variables can be used on any other place that the compiler cannot known. For instance on a external library o program.

Unused locals can be determined by the compiler. Unused globals can only be determined by the linker, since they can be shared across object files.

In general, the linker doesn't do warnings for code-gen.

When the variable is global, the compiler has not full visibility across all the compilation units in the project - the variable could be modified in another compilation unit. The linker is able to tell that it is unused, probably it will remove it from the object file.

Because if it's global it can be used by another module that gets linked in later.

It's a common idiom to have all your globals defined in a single file. That file may not even have any code, much less code that uses all the variables.

I have encountered the same question when I build the dalvikVM in android2.3 and I got the key of the point. It is because that the parameters of the compiler is too strict:

LOCAL_CFLAGS += -Werror.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top