0

In certain circumstances, the C language allows you to declare an object such as a variable without defining it.

This can be done using the keyword ‘extern’ or through the tentative definition rule for global variables (although in this case I am not sure if it's allowed by the language or the compiler. It works for me with GCC -std=iso9899:2017 -pedantic-errors).

So we can compile this without error:

int main(void)
{
    extern int a;
    extern int a;
    extern int a;
    extern int a;
    extern int a;
    extern int a;
}

Or this:

int a;
int a;
int a;
int a;

int main(void)
{
    a = 0;
}

Unless I am mistaken, in that case the compiler treats each 'int a;' as an attempt of definition until it reaches the last one which is treats as an actual definition. This means that previous attempts are regarded as mere declarations.

But if we try this with a non global object, it triggers an error of redeclaration with no linkage.

So, is redeclaration of global objects legal or illegal according to C standards? And if it is, why only for global objects?

Thank you in advance for your help.

Bey Réda
  • 57
  • 5
  • The code in the question is correct. The question in the title is "it depends", e.g. `int a = 1; int a = 1;` is not allowed . – M.M May 19 '22 at 07:39
  • 1
    Related: [About Tentative definition](https://stackoverflow.com/questions/3095861/about-tentative-definition) and [What is the rationale behind tentative definitions in C?](https://stackoverflow.com/questions/33200738/what-is-the-rationale-behind-tentative-definitions-in-c) – Weather Vane May 19 '22 at 07:45
  • Just because you declare a lot of variables with the same name does not mean that the compiler is actually including them. You are not redeclaring them, rather the compiler only cares about one of them (in second example) in order to set it to zero in function. The first example does not make any sense. – MathiasE May 19 '22 at 07:49

0 Answers0