"I was expecting const qualifier error/warning at extern int i; and read-only memory modification error in *ptr = 99; in b.c, but instead the compilation went fine."
a.b
and b.c
, although each as stand-alone are syntactically correct, each occupies its own compilation unit, with nothing tying their contents together. Their is nothing to cause a compile conflict because the contents of one have zero visibility of the contents of the other.
As written,
const int i = 9;//in a.c
and
extern int i;//in b.c
occupy two completely autonomous places in memory,and although they share the same symbol, have no relationship whatsoever, except that at run-time they are participants within the same process. (if one is not optimized out.)
It is unclear whether your question derives from the need to deploy actual code, or just as a learning project. Either way, when it is desired to have a project global variable, a proper way to do it (some would say idiomatic way) is to:
- declare an
extern
in a header file
- #include that header file in in any
.c
file that will Use it
- Finally, define it in global space once in one of the
.c
files that will use it.
Eg:
a.h
extern int i; //declare here
a.c
#include "a.h"
...
int i = 0;//define in global space and use here
//(often in file containing main() function)
b.c
#include "a.h"
...
int *ptr = &i; //use here
Now you have a single instance of globally visible variable that can be accessed from both a.c
and b.c
, As such, the potential for conflict now exists and because both .c
files can see and act on the single instance of i
, the way it is declared and defined will be scrutinized differently during compilation, across all compilation units. Inconsistencies will be seen and flagged.