I have read a lot about extern variables but no one seems to address it appropriately. If I declare and define a variable in C, it gets memory assigned in that scope of the file. but at a later stage in multi-file modular project that variable is declared as an extern which should store the it in the Data segment to exhibit the global behavior intended with the extern functionality.
So I am trying to figure out how and when the memory is being allocated, i.e. the compile time and run time behavior of the extern variable.
One of the compilation units has to define the variable as a global variable. When compiling this file, memory is allocated for the variable in the data segment, similar to file scope variables. The difference is that the variable is registered in the linkage table so that other object files can find it.
All the other compilation units declare it using the extern
keyword. This prevents them from allocating memory for the variable, and arranges for the linker to find the external variable.
When you link all the object files together, the linker finds all the object files that have the external reference to the variable, and connects that link to the memory that was allocated in the first object file.