Consider the sample code below :
File1.cpp
#include <iostream>
static int x = 6; // line 3
int main()
{
int x = 10; // line 7
{
extern int x; // line 9
x = x + 5;
std::cout << "x = " << x << "\n";
}
}
The external declaration in line 9 causes x in the following lines to refer to the static x (defined in line 3) instead of the automatic x (defined in line 7). But I get the following compiler warning:
File1.cpp:3: warning: ‘x’ defined but not used
Even with this warning, I get the expected output which is x = 11, which is 5 added to the value of the static variable x.
Why is the compiler giving the above warning? I am using GCC version g++ (GCC) 3.4.6.
Note: It would have been easier if you had numbered all lines.
You are are using an old version of GCC that doesn’t handle extern correctly. If you use a modern version, you’ll see three issues with your code.
First, the local x in main() is not used (warning). Second, the static global x is not used (warning). Third, the external x is not defined(error).
Either you should not declare the global x static, or you should use ::x with no extern specification.