Home >Backend Development >C++ >How Do Global and Static Variables Behave in Dynamically Linked Shared Libraries Across Different Operating Systems?

How Do Global and Static Variables Behave in Dynamically Linked Shared Libraries Across Different Operating Systems?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 05:45:14853browse

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:

  • Extern global variables are not visible outside the defining module.
  • To export a global variable, it must be declared with __declspec(dllexport) in the DLL and __declspec(dllimport) in the importing module.

Unix-like Systems:

  • Extern global variables are visible and shared across all modules loaded during load-time dynamic linking.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn