views:

1276

answers:

2

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 ?

A: 

Yes. The differences between the different sort of static variables are:

  • the scope

  • the initialization time for those which are dynamically initialized.

The implementation (and note BSS and DATA segments are implementation details) is usually the same. To ensure the correct initialization of dynamically initilized static function variables, one way is to add an additional boolean one indicating that dynamic initialization is needed.

AProgrammer
+2  A: 

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.

Rob K
So, if I understand you correctly, if multiple processes link to this shared library, the variable will behave as a 'static' across invocations by different processes ?
nagul
No, effectively a new instance of the DLL is loaded for each process that connects to it, so data segments are not shared between processes.
Rob K
Understood. The DLL gets its own memory sections, and the static variable goes in there.
nagul