4

I have one doubt if i declared global variable with static.

file1.c

static int a=5;

main()
{
   func();
}

can it be access in another file2.c using extern ?

file2.c

func()
{
   extern int a;
   printf(a);
}

or only global variable declared without static can be access using extern?

Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
david
  • 413
  • 5
  • 20
  • static and extern are in a way each other's opposites. So your question is similar to: "I went to the paint store, they had red and blue paint. I bought red. How do I use my red paint to paint my house blue?" – Lundin Nov 05 '12 at 08:23

3 Answers3

13

No!
static limits the scope of the variable to same translation unit.
static gives the variable an Internal Linkage and this variable cannot be accessed beyond the translation unit in which was created.

If you need to access a variable accross different files just drop the static keyword.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • so only global variables without static declaration can access in another file with ectern?? or what is the use of extern?? – david Nov 05 '12 at 07:53
4

No. A a in file1.c names a variable with internal linkage. The same name used from a different translation unit will refer to a different variable. That might also have internal linkage or it might (as in this case) have external linkage.

Within the same file you can refer to a file scoped variable with internal linkage with extern, though.

static int a;

int main(void) {
    extern int a; // still has internal linkage
    printf("%d\n", a);
}
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
2

That seems to be a misunderstanding of the two meanings of static:

  • for global declarations static means restriction to translation unit, so static is exactly meant to prevent what you are trying to do
  • for local variables static is a storage class, meaning that the variable keeps its value between function calls. For global variables (on module level, i.e. outside of functions) this is always the case, so static is not needed.
guidot
  • 5,095
  • 2
  • 25
  • 37