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?

doraemon1
  • 113
  • 1
  • 11
  • 3
    `int a;` defines the variable. Yet `extern int a = 10;` *also* defines it. There should be only one definition. So I suggest you change it to `int a = 10;` in the first file and `extern int a;` in the second file, which makes it only a declaration. – Weather Vane May 30 '21 at 13:39
  • I think this shows a general lack of understanding of the extern keyword, not that there is anything wrong with that, how ever I dug through my notes and flagged this as a decent source that explains the keyword. https://www.journaldev.com/38985/extern-keyword-in-c – Sorenp May 30 '21 at 13:46
  • Why would you want to do this? – August Karlstrom May 30 '21 at 14:11
  • someone asked this to me. – doraemon1 May 30 '21 at 14:14
  • @도라에몽1 It's better to declare the variable in a header file. – August Karlstrom May 30 '21 at 14:15
  • But in a.c "int a" isn't a temptative definitions? – doraemon1 May 30 '21 at 14:16
  • if a.c "int a=3" b.c "int a" a=3 is external linkage so doesn't int a terns out to external int a? – doraemon1 May 30 '21 at 14:17

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
  • 138,810
  • 21
  • 208
  • 365
  • 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? – doraemon1 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___________
  • 60,014
  • 4
  • 34
  • 74