Search code examples
ckeywordextern

Is extern keyword in C redundant?


I have found that I could achieve the desired results without using extern (though I do agree that it gives reader some kind of an hint about the variable). In some cases using extern gave undesired results.

xyz.h

int i;

file1.c

#include "xyz.h"
....
i=10;
....

file2.c

#include "xyz.h"
main()
{
printf("i=%d\n",i);
}

Of course, it was a large project, broke it down for simple understanding. With extern keyword, I couldnt get desired results. In fact, I got linker error for the variable i with "extern" approach.

Code with "extern" approach,

file1.c

int i;
main()
{
i=10;
}

file2.c

extern int i;
foo()
{
printf("i=%d\n",i);
}

This gave linker error. I just wanted to know why it worked in the first case and also the practical case where we cannot do it without using the keyword "extern". Thanks.


Solution

  • There are at least 2 cases where extern is meaningful and not "redundant":

    1. For objects (not functions) at file scope, it declares the object with external linkage without providing a tentative definition; tentative definitions turn into full definitions at the end of a translation unit, and having the same identifier defined with external linkage in multiple translation units is not permitted.

    2. At block scope (in a function), extern allows you to declare and access an object or function with external linkage without bringing the identifier into file scope (so it's not visible outside the block with the declaration). This is useful if the name could conflict with something else at file scope. For example:

      static int a;
      int foo(void)
      {
          return a;
      }
      int bar(void)
      {
          extern int a;
          return a;
      }
      

      Without the extern keyword in bar, int a; would yield a local variable (automatic storage).