I'm trying to understand the ways in which a C global variable can be shared between multiple files (compilation units). I've read the excellent question and answer here. However after doing a few tests I'm still left with some stuff I don't get:
Basically my question would be: if there's a variable declared (but not defined) in a header WITHOUT the extern
keyword, is it ok to simply include that header in various compilation units in order to make available that variable to all those compilation units? In this scenario it's implied that one (and only one) compilation unit contains the code for initializing (defining?) that variable, and it will be called first before the other compilation units try to do anything with that variable. If all this is true, is this procedure what's called "implicit extern" ?
I'll illustrate my question with an example:
Header "MyCommonHeader.h" contains:
//MyCommonHeader.h
int* i; //pointer to an 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() {
i = malloc(sizeof(int));
changeIt(10);
*i = 23;
}
Does the above code operates with the same i variable everywhere? Do I need to add extern
anywhere?