Can a static declared global variable be accessible with extern in another file?

I have one doubt that I declared a global variable with statics.

file1.c

static int a=5; main() { func(); } 

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

file2.c

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

or is it only a global variable declared without static that can be accessed using extern?

+4
source share
3 answers

No!
static limits the scope of a variable to the same translation units .
static gives the Internal Relationship variable, and this variable cannot be obtained outside the translation unit in which it was created.

If you need to access the variable in different files, just release static .

+13
source

No. A a in file1.c denotes an internally linked variable. The same name used from another translation unit will refer to another variable. It may also have an internal connection or may (as in this case) have an external connection.

Inside the same file, you can reference an area variable with internal binding with extern .

 static int a; int main(void) { extern int a; // still has internal linkage printf("%d\n", a); } 
+4
source

This seems like a misunderstanding of two static values:

  • for global declarations, static means limiting the unit of translation, so static is precisely designed to prevent what you are trying to do
  • for local variables, static is the storage class, which means that the variable retains its value between function calls. For global variables (at the module level, that is, outside functions) this is always the case, so static is not needed.
+2
source

Source: https://habr.com/ru/post/1444057/


All Articles