Explicitly specifying locations for symbols in ld

2019-07-20 15:24发布

问题:

Let's assume that I have the following C code:

extern int f_1();
extern int g_1();

extern int f_2();
extern int g_2();

extern int f_3();
extern int g_3();

int main(int argc, char **argv) {
    // Using f_1, f_2, f_3 and g_1, g_2, g_3 here:
    ...
}

And I want to build it by linking with 3 different libraries: l1, l2, l3 -- assuming each of them exports its own f and g functions -- so that:

  • f_1 and g_1 will be resolved to f and g respectively from l1;
  • f_2 and g_2 will be resolved to f and g respectively from l2;
  • f_3 and g_3 will be resolved to f and g respectively from l3.

Is this possible with gcc and ld:

  1. Is this possible if l1, l2, l3 are shared libraries (.so)?
  2. Is this possible if l1, l2, l3 are archives (.a)?

回答1:

objcopy's --redefine-sym option is your friend:

--redefine-sym old=new

Change the name of a symbol old, to new. This can be useful when one is trying link two things together for which you have no source, and there are name collisions.

--redefine-syms=filename

Apply --redefine-sym to each symbol pair "old new" listed in the file filename. filename is simply a flat file, with one symbol pair per line. Line comments may be introduced by the hash character. This option may be given more than once.

Apply it to you libraries l1, l2, l3. It should work both for .a and .so.



标签: c gcc ld