0

This code works fine when I re-declare the variable x in global scope:

#include <stdio.h>
#include <stdlib.h>

int x = 12;
int x;

int main() {
  printf("%d", x);
  return 0;
}

However, this code gives me an error: "redeclaration of 'x' with no linkage"

#include <stdio.h>
#include <stdlib.h>
int main() {
  int x = 12;
  int x;
  printf("%d", x);

  return 0;
}

I have learned that redefinition is not allowed more than once but redeclaration is allowed. Is this true only for global variables?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
risot
  • 9
  • 1
  • https://youtu.be/fO4FwJOShdc?list=PLBlnK6fEyqRhX6r2uhhlubuF5QextdCSM&t=311 – risot Mar 25 '20 at 15:17
  • 1
    Does this answer your question? [Redeclaration of global variable vs local variable](https://stackoverflow.com/questions/21275992/redeclaration-of-global-variable-vs-local-variable) – ThatsJustCheesy Mar 25 '20 at 15:54

1 Answers1

1

The rules around linkage and declaration are complicated and hard to summarize. In part, they developed over time, and the rules had to accommodate old software written with old rules.

The relevant rule in this case is in C 2018 6.7 3:

If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except that:

— a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type;

— tags may be redeclared as specified in 6.7.2.3.

Your identifier is not a typedef name or a structure or union tag, and it has no linkage because it is declared inside a block without extern, so there shall be no more than one declaration of it in that scope.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312