How/when memory is assigned to global variables in C

Viewed 291

I am aware of C memory layout and binary formation process. I have a doubt/query regarding the phase when and who assigns address to global variables.

extern int dummy;  //Declared in some other file  
int * pTest = &dummy;

This code compiles well. Here pTest will have address of dummy only if address is assigned to it. I want to know in which phase (compilation or linker) does dummy variable gets address?

2 Answers

The compiler says:

int *pTest = &<where is dummy?>;

The linker says:

int *pTest= &<dummy is here>;

The loader says:

int *pTest= <dummy is at 0x1234>;

This somewhat simplified explanation tries to convey the following:

  • The compiler identifies that an external variable dummy is used

  • The linker identifies where and in which module this variable resides

  • But only once the executable program is placed in memory is the actual location of the variable known and the loader puts this actual address in all the places where dummy is used.

the actual process is actually a bit different.

The compiler saves the information in the object file about the the assignment and the external object reference.

The linker depending on the actual hardware IS and implementation calculates the absolute address ( if the code will be placed at the fixed address - for example the embedded uC project) or same virtual and sets the entry in the relocation table (If the code is position independent) and the loaded is changing this virtuall address to the correct one during the program loading and start-up.

Related