Assume that a global variable defined in a shared module is referenced in module.c:
1 extern int Global ; 2 3 int foo () {4 Global 1 ; 5 }
The compiler cannot determine whether the definition of the variable global is inside or outside the module. Assume that module.c is a source file for an executable file, that executables are not PIC and will not be repositioned. The linker creates a copy of the global variable in the. BSS segment, which causes the same variable to exist in multiple locations simultaneously. The solution to the problem is to have all access to the variable global point to that copy in the executable file.
ELF shared library at compile time, all global variables are considered to be defined in other modules by default, and external access is achieved through the GOT table. When a shared module is loaded, if a global variable has a copy in the executable file, the dynamic linker points the corresponding address in the GOT table to that copy. If the variable does not have a copy in the executable file, the corresponding address in the GOT table points to the copy of the variable inside the module.
Suppose a global variable G is defined in libx.so, and both processes A and B use libx.so. So when libx.so is loaded by two processes, its data segments have separate replicas in each process, so processes A and B access are copies of the global variable G in their own processes, with no effect on each other. But if they are threads A and B of the same process, they are accessing the same copy.
Sometimes you want different threads in the same process to access different copies of the global variables, which can avoid interference between threads on global variables, or avoid thread synchronization. This can be done through thread-private storage (thread Local Storage, TLS). In the Android system, TLS is implemented with the help of a coprocessor, and the code for TLS can be seen in the implementation of functions such as Linker and Getpid.
It is also sometimes desirable for multiple processes to share a copy of the same global variable to enable interprocess communication. Remember when you used to write Windows DLLs, there is the concept of "shared data segments" to implement this.
Learning materials: Self-cultivation of programmers-links, loading and libraries
Learn about dynamic links (iii)--global variable issues for shared modules