Static variable behaving like a global variable in C -


i have 2 files. 1.c , 2.c

there static variable defined in 1.c. able access , modify static variable in 2.c using keyword extern variable in 2.c. how possible? if static variable can accessed in other files this, purpose of scope of static variables.

1.c

static int block_no; 

2.c

extern int block_no; block_no = 5; 

the way if you've somehow put both identifiers in same translation unit (such if 2.c #include "1.c").

the relevant portion of standard 6.2.2 linkages of identifiers (a), starting /2:

2 in set of translation units , libraries constitutes entire program, each declaration of particular identifier external linkage denotes same object or function. within 1 translation unit, each declaration of identifier internal linkage denotes same object or function. each declaration of identifier no linkage denotes unique entity.

3 if declaration of file scope identifier object or function contains storage-class specifier static, identifier has internal linkage.

4 identifier declared storage-class specifier extern in scope in prior declaration of identifier visible,23) if prior declaration specifies internal or external linkage, linkage of identifier @ later declaration same linkage specified @ prior declaration. if no prior declaration visible, or if prior declaration specifies no linkage, identifier has external linkage.

point 4 relevant if had combined them single translation unit. if you're compiling them separately 2 block_no variables distinct since static 1 have internal linkage.

that's not there isn't defined block_no somewhere else external linkage may being picked up. otherwise compiler should complain missing block_no in 2.c since, while file declares variable, doesn't define ("declare" means declare exists somewhere else, "define" means create here).


(a) that's c99 quick glance @ c11 shows hasn't changed.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -