Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I share code across static libraries without duplicate symbol errors?

I am new to building static libraries and would like to create 2(+) libraries each of which has some unique code and some shared code. My intention is that other projects will link one or more of these static libraries.

Util.h/m  <-- Shared
ImplOne.h/m  <-- Unique to 'ImplOne'
ImplTwo.h/m  <-- Unique to 'ImplTwo'

I am using XCode and generating the libraries by building Util.m and ImplOne.m in one case, and Util.m and ImplTwo.m in the other.

Of course the issue is that I now cannot use these libraries together because they will have duplicate symbols. What is a better architecture for this situation?

like image 758
Ben Flynn Avatar asked Mar 30 '26 19:03

Ben Flynn


2 Answers

I think the cleanest alternative would be to make a separate library for the shared Utils.h/m. The drawbacks are that your users would need to link utils along with implone and/or impltwo, and that in order to link impoone and impltwo together both libraries need to be compiled with the same version of utils. In return, the source of the libraries would stay nice and clean.

An alternative would be to use macros to alter function and variable names in the utils to avoid linker errors. The most important consequence of this is code duplication: both implone and impltwo would link identical pieces of code under different names. The other one is readability: it would suffer tremendously, because each reference to a function in utils would need to be wrapped in a macro. This makes the second approach dirty, so I would definitely recommend making utils a separate library.

like image 152
Sergey Kalinichenko Avatar answered Apr 02 '26 12:04

Sergey Kalinichenko


I have a similar problem to this in a current codebase. My solution is similar to the answer that just came in as I wrote this, but I'll leave it here as a comparison/reference.

I have a common static library project (let's call it libCommonBits.a). I have a second static library which has some UI code in it (let's call that libCommonUI.a), which also depends on libCommonBits.a. My main app needs to use both libraries.

My solution is to not actually link the libCommonBits.a into the libCommonUI.a. It compiles against the header files fine, and just means that my main app links against two static libraries instead of one.

I'm hoping this approach is taken on by more people distributing libraries. It's frustrating when you use a static library that has already linked in common libraries (JSONKit or similar), and you also use that separately in your codebase. In that case, the symbol renaming might be the only solution.

like image 45
Stew Avatar answered Apr 02 '26 12:04

Stew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!