Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of static variables in dynamically linked libraries (C/C++)

As discussed here, a static variable is stored in the .BSS or .DATA segment.

Where is this memory stored if the static variable is inside a function that's in a dynamically linked library ? Does storage for this variable get allocated in the .BSS or .DATA segment of the linking process at the time of linkage ?

like image 284
nagul Avatar asked Jul 28 '09 12:07

nagul


People also ask

What is static library and dynamic library in C?

In C exist two kinds of libraries the first ones are the static that allows us to link to the program and are not relevant during the runtime, and the other ones are called dynamic libraries those are preferable use when you run a lot of programs at the same time who are using the same library and you want to be more ...

What are the properties of static variable in C?

Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

What is difference between static and dynamic linking?

By using dynamic linking, you can upgrade the routines in the shared libraries without relinking. This form of linking is the default and no additional options are needed. Static linking means that the code for all routines called by your program becomes part of the executable file.

What is a dynamic library in C?

Dynamic libraries provide a means to use code that can be loaded anywhere in the memory. Once loaded, the library code can be used by any number of programs. This way the size of programs using dynamic library and the memory footprint can be kept low as a lot of code is kept common in form of a shared library.


1 Answers

The static variable is going to end up in the .BSS or .DATA section of the DLL file. The executable that links to the DLL probably won't even know it exists. When the EXE loads the DLL, the system sets up the DLL's data sections for it, and then calls the DllMain(). That's when the DLLs statics come into existence and get initialized.

like image 175
Rob K Avatar answered Nov 09 '22 10:11

Rob K