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

global variables in shared libraries

Hi there,

Please excuse the OTness of this post. Since I am writing a library
to be included in Debian, I feel that I should not be slaughtered
for bothering you and hoping for your time and knowledge. This was
on d-u until people told me that it would be less OT here. Thus,
a repost...

I have a question about shared libraries and C. Even though I did
search the web, I could not find a reliable answer. I am writing
a shared library with the intention to make it reentrant and
thread-safe, if these concepts even apply.

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. 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 ;^>.

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.

I'd be interested to hear your opinions, and how you deal with these

Please do not CC me when replying to lists; I read them!
 .''`.     martin f. krafft <madduck@debian.org>
: :'  :    proud Debian developer, admin, and user
`. `'`
  `-  Debian - when you have better things to do than fixing a system
Invalid/expired PGP subkeys? Use subkeys.pgp.net as keyserver!

Attachment: signature.asc
Description: Digital signature

Reply to: