Home >Backend Development >C++ >How Do Global and Static Variables Behave in Dynamically Linked Shared Libraries Across Different Operating Systems?
Dynamically Linked Global and Static Variables in Shared Libraries
Load-Time Dynamic Linking
When an application dynamically links to a module A with load-time linking, the operating system loads the DLL's code and data into the application's address space. The application has its own copy of A's global and static variables, loaded into its data segment.
Run-Time Dynamic Linking
With run-time dynamic linking, the application loads the DLL's code and data only when needed. The application does not get its own copies of A's global and static variables. Instead, it accesses them directly from the loaded DLL.
Visibility and Scope
In all cases, static variables are only visible within the module where they are defined. Global variables, however, have different visibility rules:
Windows:
Unix-like Systems:
Multiple Applications
If multiple applications use modules A and B, separate copies of their global and static variables are created for each application, even if they are in different processes.
DLL Access to Application Globals
DLLs do not have direct access to the global variables of the application they are linked to. In order to manipulate the application's global variables, the DLL must use exported functions provided by the application.
Conclusion
The behavior of global and static variables in dynamically linked shared libraries varies between Windows and Unix-like systems. Windows enforces strict separation of globals between modules, while Unix-like systems allow sharing of globals during load-time dynamic linking. In general, it is recommended to avoid using global variables when working with shared libraries.
The above is the detailed content of How Do Global and Static Variables Behave in Dynamically Linked Shared Libraries Across Different Operating Systems?. For more information, please follow other related articles on the PHP Chinese website!