C implicit extern for global variable, when does it happen, how does it work -


i'm trying understand ways in c global variable can shared between multiple files (compilation units). i've read excellent question , answer here. after doing few tests i'm still left stuff don't get:

basically question be: if there's variable declared (but not defined) in header without extern keyword, ok include header in various compilation units in order make available variable compilation units? in scenario it's implied 1 (and one) compilation unit contains code initializing (defining?) variable, , called first before other compilation units try variable. if true, procedure what's called "implicit extern" ?

i'll illustrate question example:

header "mycommonheader.h" contains:

//mycommonheader.h int* i; //pointer int 

file myfirstheader.h contains:

//myfirstheader.h void changeit(int newvalue); 

file myfirstsource.c contains:

//myfirstsource.c #include "myfirstheader.h"   void changeit(int newvalue) {     *i = newvalue;  } 

file mysecondsource.c contains:

//mysecondsource.c #include "mycommonheader.h" #include "myfirstheader.h"  void main() {    = malloc(sizeof(int));    changeit(10);    *i = 23; } 

does above code operates same variable everywhere? need add externanywhere?

/* file.h */ int* i; 

is tentative definition of i variable. means if there no other (external) definition variable in translation unit, defined once (initialized 0). if there 1 matching (external) definition of i elsewhere in translation unit, definition used, , tentative definition above behave declaration.

as common extension, compilers extend behavior across translation units. means, such compilers, can safely include header file in many translation units want, , there still 1 definition of i.

it have been different if had explicitly initialized i in header file :

/* file.h */ int* = 0; 

this actual definition (not tentative), , can include header file in 1 compilation unit, or you'd multiple definition error.

the better way, define variable in .c file, , use extern in header file :

/* file.h */ extern int* i;  /* file.c */ int* = 0; 

this makes absolutely clear there 1 definition (the 1 in .c file), , every compilation unit header file included refer definition.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -