How to overwrite existing symbol when linking?

1.1k Views Asked by At

I am having two libs A and B. there having the same function same_func, I don't want to modify A's code to remove same_func in A but override the symbol when linking. is there any way to indicate the function in B lib having a higher priority to be chosen first if symbol conflicted.

2

There are 2 best solutions below

0
On

The order of the libraries on the command line commonly decides. Put library "B" before library "A".

If your application has a reference to same_func() and you set library "B" as the first one, the linker will resolve it to B's same_func(). Since the reference is resolved now, linking with library "A" will only resolve the references not yet resolved.

0
On

A safer solution could be to make all or relevant symbols in libA as 'weak'. You can do this with objcopy using option --weaken. This would make sure that linker chooses definitions from libB if it's available in both A and B. Another solution would be to make use of linker script to include or exclude specific sections from particular objects.