4

I am working with a library that is somewhat poorly written. In order to function, it requires several global variables to be declared and sometimes even maintained by my own code. I really don't like having to put a whole list of global variables at the start of my main file, and even less also having to extern them all in the .h file too.

Is there a good way (or at least, a less-bad way) to deal with this unfortunate situation?

5
  • How would you have done it? Given this is tagged C, OOP is out the window?
    – Flater
    Commented Jul 18, 2023 at 0:03
  • Yes, it's C, no real OOP available. I think what I'd like to do is make a file that "finishes" the library, and then use that whenever I need to use this library. However, I thought I'd ask and see if there are any best-practice solutions for this situation - I'm very inexperienced at programming (my first job out of a largely unrelated degree) and want to try to do everything 'properly'. Commented Jul 18, 2023 at 1:21
  • I was asking how you would've done it, rather than how you would deal with it in its current state. It's not clear precisely what the issue is.
    – Flater
    Commented Jul 18, 2023 at 3:17
  • There are techniques for data hiding in C even if they are a bit kludgy. If you push C hard enough you can turn it into C++. At a certain point your biggest problem is going to be how much you're surprising people. On the other hand, you can use C libraries in C++. Commented Jul 18, 2023 at 6:29
  • Do you only have the lib avaible in binary form + header?
    – Doc Brown
    Commented Jul 18, 2023 at 10:39

1 Answer 1

13

Assuming that you cannot change the library, and you have to use it, you need to have these global variables somewhere in your code.

I’d recommend implementing an interface module that the rest of your application calls instead of calling the library directly; that module could be plain C, it could be some class, whatever you would have wanted if you had been free to design and implement the library yourself.

That interface module declares and maintains the global variables needed, and hides that ugliness from the rest of your code. Even header files of that library would only be imported by your interface module, and nobody else.

2
  • 3
    +1, this is the classical use case for an anti-corruption layer. Commented Jul 19, 2023 at 6:57
  • This seems like a good solution, and more well-refined than I was thinking of (although it is similar). Commented Jul 19, 2023 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.