Calm down guys. There are 2 parts of questions here:
- Why function complaint about unused variables?
- What happened to package level’s unused (private) variables?
For the 1st question: it is because function is part of stack memory storing execution data. If you declare but unused variable, a portion of memory will be allocated and wasted. Another good reason for removing them is to reduce potential memory related bugs as a whole.
@petrus answered the in-depth technical aspect correctly: the compiler does compile functions which hence has the visibility of the unused function.
That is why the compiler will and always complain about unused variables inside a function.
As for your second part of the answer, I could not find a proper spec mentioning about their unused consequences either. In fact, because of your interesting question, I actually tweeted to one of the developer asking help to locate that documentation for answering this question.
Like @NobbZ said, which sparked my curiosity as well: why didn’t the linker complains about it?! My hunch tells me you had found a bug but there are no supporting evidences. Hence, the tweet is needed.
There is a quick and hackish way: compile a hello world with unused package-level variable and dissemble it and then then analyze the assembler codes to locate the variable. However, I’m a bit tight in schedule so if anyone is interested, please go ahead and try it out (use
amd64 CPU as their datasheet is much easier to read):
As for why it slipped through my sensors: because I don’t leave unused codes (not just variable) in any of my authorship (why would I?).
Secondly, I rarely use package level variables (both exported and private). Haven’t found any practical use cases for it. However, I used A LOT of constants.