Why the following doesn’t compile?
...
extern int i;
static int i;
...
but if you reverse the order, it compiles fine.
...
static int i;
extern int i;
...
What is going on here?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is specifically given as an example in the C++ standard when it’s discussing the intricacies of declaring external or internal linkage. It’s in section 7.1.1.7, which has this exert:
Section 3.5.6 discusses how
externshould behave in this case.What’s happening is this:
static int i(in this case) is a definition, where thestaticindicates thatihas internal linkage. Whenexternoccurs after thestaticthe compiler sees that the symbol already exists and accepts that it already has internal linkage and carries on. Which is why your second example compiles.The
externon the other hand is a declaration, it implicitly states that the symbol has external linkage but doesn’t actually create anything. Since there’s noiin your first example the compiler registersias having external linkage but when it gets to yourstaticit finds the incompatible statement that it has internal linkage and gives an error.In other words it’s because declarations are ‘softer’ than definitions. For example, you could declare the same thing multiple times without error, but you can only define it once.
Whether this is the same in C, I do not know (but netcoder’s answer below informs us that the C standard contains the same requirement).