Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are global variables in shared libraries linked?

Tags:

c++

c

linux

dll

Suppose I have shared library with this function where "i" is some global variable.

int foo() {
return i++;
}

When I call this function from multiple processes the value of "i" in each process is independent on the other processes.

This behavior is quite expected.

I was just wondering how is usually this behavior implemented by the linker? From my understanding the code is shared between processes, so the variable has to have the same virtual address in all address spaces of every program that uses this library. That condition seems quite difficult to accomplish to me so I guess I am missing something here and it is done differently.

Can I get some more detailed info on this subject?

like image 687
Honza Brabec Avatar asked Jun 15 '13 18:06

Honza Brabec


2 Answers

The dynamic linking process at run time (much the same as the static linking process), allocates separate data (and bss) segments for each process, and maps those into the process address space. Only the text segments are shared between processes. This way, each process gets its own copy of static data.

like image 58
Ziffusion Avatar answered Sep 30 '22 05:09

Ziffusion


the code is shared between processes, so the variable has to have the same virtual address in all address spaces of every program that uses this library

The code is not shared the way you think. Yes the dynamic shared object is loaded only once but the memory references or the stack or the heap that code in the so uses is not shared. Only the section that contains the code is shared.

like image 38
Cratylus Avatar answered Sep 30 '22 06:09

Cratylus