[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: global variables in shared libraries



On Thu, Jan 22, 2004 at 11:34:39PM +0100, martin f krafft wrote:
> My question is about global variables -- I know they are bad
> programming style, but when it comes to debugging or subsystem
> initialisation in C, they are sometimes really necessary.

> If I use a global variable in a shared library, is it shared among
> all instances using that library? Here, I would say no because
> a process' memory space is separate from another's.

> However, what happens when I have a threaded process us the library?

> I have come up with two ways to deal without global variables in C:

> The first is to expect the user to instantiate a struct, e.g.
> a struct global_settings and pass it along to each function of the
> API.

Yes, this is often called a "context" struct, and pointers to such
structs are often passed as "handles" in many libraries.  This is the
more or less canonical way to track library state between multiple
function calls.

> This is cumbersome but would work, although I could not be
> assured that it's always the same instantiation -- the user could
> create two objects and pass them alternatingly, thereby messing with
> the integrity of the global settings and the library code. It is
> questionable whether I should guard against such a case, but I feel
> like it ;^>.

Why?  Why should the user not be allowed to declare two separate
contexts for his use of the library, within a single process?

> The other approach seems cleaner: I declare "extern" variables in
> the interface and expect the user to instantiate them, while I use
> them freely in the code. The problem here is that the user would
> have to do so on a global level in his/her code, so we'd have the
> same problem again, albeit the responsibility would be shifted from
> the library to the user code. I am not sure this is preferable.

No, ick, this creates a shared library with references to undefined
symbols, which means you lose all the protection the linker offers in
ensuring that your libraries aren't mislinked.  (It also breaks
prelinking.)

-- 
Steve Langasek
postmodern programmer

Attachment: pgpvjA8oEqEIL.pgp
Description: PGP signature


Reply to: