0

I surprised when compiled following program on GCC compiler. It's successfully worked. Compiler gives only warning.

warning: 'i' initialized and declared 'extern' [enabled by default] extern int i = 10; ^

My code:

#include <stdio.h>
 //Compiler version gcc 4.9
extern int i = 10;
 int main()
 {
    printf("%d\n",i);
    return 0;
 }

Output:

10

Why doesn't give compiler error? Is it undefined behavior?

msc
  • 33,420
  • 29
  • 119
  • 214
  • possible duplication http://stackoverflow.com/questions/496448/how-to-correctly-use-the-extern-keyword-in-c – 0xAX Feb 27 '17 at 17:59

1 Answers1

-1

You should not put your main function body in a header, but rather in a .c-file. Vice versa, you should not put extern in a .c-file but only in a header. That is the difference between declaration and definition.

Extern means, make this variable known, but there is no memory to be reserved for it. The compiler now says: Ok, I know you want this variable to be used, but it is only promised to be there, not actually defined.

The compiler anyway does not know about other objects (other .c-files) that might define this variable. So it keeps it to the linker to actually try to gather all variables.

If the linker now does not find that variable elsewhere, it implicitly makes the variable local, but warns about the broken C-standard.

Psi
  • 6,387
  • 3
  • 16
  • 26