views:

978

answers:

6

Hello,

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.

+6  A: 

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.

anon
But to make it visible, I need to declared it external right?.
Eduardo
No, it's visible by default. External is used in other compilation units to indicate to the linker to look for the global elsewhere.
Michael
Nope - the other compilation unit can do that.
anon
No, just don't declare it static. If you want the warning, make it static.
Pete Kirkham
It only needs to be declared extern in the module that uses the variable, not necessarily the module that defines the variable.
Michael Burr
nope, to make it invisible, you need to declare it static
1800 INFORMATION
+3  A: 

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

FerranB
+1  A: 

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.

Michael Burr
+3  A: 

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.

Michael
Generally, if a linker is going to do anything with unused globals, it's going to remove them from the image.
Michael Burr
+2  A: 

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.

1800 INFORMATION
I've never come across alinker that removes things from object files. From the final executable, maybe.
anon
Sorry that is what I meant
1800 INFORMATION
+3  A: 

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.

paxdiablo