0

I defined extern a in the scope and outside of the scope

a.c

int a;

void foo(void)
{
    a = 3;
}

b.c

extern int a = 10; /*same as "extern a; int a = 10?" */


void foo(void);

int main(void)
{
    foo();
    printf("%d", a);
}

Is this code well-defined?

도라에몽1
  • 49
  • 1
  • 7

2 Answers2

2

This causes undefined behaviour in Standard C due to multiple definition of a.

There is a common extension for implementations to allow multiple definition so long as at most one is initialized.

For more detail see: Is having global variables in common blocks an undefined behaviour?


extern int a = 10; is the same as int a = 10; which is the same as extern int a; int a = 10; . Variable definitions have external linkage unless specified as static (or the identifier already declared as static in the same scope).

M.M
  • 134,614
  • 21
  • 188
  • 335
  • thank you but int a; is temptative definition and there is external definition so doesn't int a changes to declaration? is it still definition? – 도라에몽1 May 30 '21 at 16:04
1

extern int a = 10; is the same as int a = 10;

If you have both the code will not link as there will be multiple definitions of the static storage variable a in your project.

0___________
  • 47,100
  • 4
  • 27
  • 62