views:

111

answers:

2

I have a cpp file from which I am generating a shared library (using autofoo and the like). Within the cpp file, I have declared a couple of static fields that I use throughout the library functions.

My question is 2-part:

1) Where are these fields stored in memory? It's not as if the system instantiates the entire library and keeps it in memory... the library, after all, really is just a bunch of hooks.

2) Is there a better way to do this? The reason I did it to begin with is that I want to avoid requiring the user to pass the fields into every library function call as parameters.

Thanks!

+1  A: 

The code used to load shared libraries:
Generally (each has minor technical differences):

  • Loads the shared lib into memory
  • Walks the symbol table and updates the address of function in the DLL
  • Initializes any global static members using their constructor.

Note: The shared lib loader need not do all this at the load point.
It may do some of these jobs lazily (implementation detail). But they will be done before use.

Any Global staic POD variables (things with no constructor). Will be stored in special memory segments depending on weather they are initialized or not (again an implementation detail). If they were initialized then they will be loaded with the from disk (or shared lib source) with that value already defined.

So the answer to your questions:

  • undefined.
    • The library is code segments
    • Initialized data segments
    • Uninitialized data segments
    • Some utility code that knows how to link it into a running application.
  • Better than what exactly
    • Good practice would suggest passing values to a function rather than relying on global state. But to be honest that is an over generalization and really down to the problem.
Martin York
A: 

Logically speaking, it is as if the system instantiates the entire library. In practice, only the code is really "shared" in a shared library, anybody who links against it will get a copy of the data. (Well maybe not read-only data). So, as far your questions go:

1) Your process will get a copy of the variable somehow (dependent on how the shared library system on your OS works).

2) I don't see a problem with this approach.

Carl Norum