Search code examples
c++clinkerstatic-librariesweak-linking

Prevent symbol from static to override libc symbol


I have a static library which I don't control that defines the symbol gettimeofday(). The main function needs to use this function but I don't want it to use the one from the library, I just want the regular function from the system to be used. How can I make the linker prefer the function from the system libraries?
I am on macOS using clang.
Things I tried:

  • linking the library with -weak-l. This didn't work. I thought this would make the "strong" reference in the system lib to override the one in the static lib but apparently it didn't. Maybe the meaning of "weak" is slightly different in macOS than on Linux?

  • reordering the linker command line. I tried putting -lc before the static lib and it didn't make a difference. I'm not quite sure what lib this symbol comes from. Related question: is there a way to make ld say which library it got a symbol from?

  • I thought about maybe renaming all the symbols in the library to have some prefix but llvm_objcopy which seem to do that doesn't support Mach-O objects.


Solution

  • Since you are building on macOS, use -lSystem before the static library, not -lc.

    This will result in a linker warning that it is “ignoring duplicate libraries: '-lSystem'”. If you wish to avoid that, you can use Clang’s -v switch to have it output the link command it uses, then reproduce that link command yourself with the later -lSystem omitted.