如何避开“多个定义的符号”在与gcc链接 [英] How to get around "multiple defined symbols" in linking with gcc
问题描述
我使用的是具有gcc 2.95.3的旧系统,我必须链接两个对象,尽管它们之间没有任何关系,但它们都有相似的命名方法。我不能重命名其中的任何一个,但我希望有一种方法可以构建它们,以免连接器发生抱怨。它所抱怨的方法都是由对象内部的类在内部调用的。我可以做什么?
I am using an older system that has gcc 2.95.3, I have to link in two objects that although they have nothing to do with each other, they each have similarly named methods. I can't rename either of them, but I would hope there is a way to build them as to not have the linker complain. The methods it is complaining about are each internally called by classes within the object. What can I do?
推荐答案
如果你有一个完整的GNU工具链,你应该可以解决你的问题,使用 objcopy
,像这样(如果我已经正确理解你的问题):
If you have a complete GNU toolchain, you should be able to work around your problem using objcopy
, like this (if I've understood your problem correctly):
这里有两个非常相似的对象,foo 和bar,它们都会导出一个名为冲突
的符号 - 它在内部使用,但根本不需要导出:
Here are two very similar objects, "foo" and "bar", both of which export a symbol called clash
- which is used internally, but doesn't really need to be exported at all:
$ cat foo.c
#include <stdio.h>
void clash(char *s) { printf("foo: %s\n", s); }
void foo(char *s) { clash(s); }
$
和
$ cat bar.c
#include <stdio.h>
void clash(char *s) { printf("bar: %s\n", s); }
void bar(char *s) { clash(s); }
$
以下是主代码,它们都使用这两个代码:
And here's the main code, which wants to use both:
$ cat main.c
extern void foo(char *s);
extern void bar(char *s);
int main(void)
{
foo("Hello");
bar("world");
return 0;
}
$
将它们连接在一起不起作用:
Linking them together doesn't work:
$ gcc -Wall -c foo.c
$ gcc -Wall -c bar.c
$ gcc -Wall -c main.c
$ gcc -o test main.o foo.o bar.o
bar.o: In function `clash':
bar.c:(.text+0x0): multiple definition of `clash'
foo.o:foo.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status
$
因此,使用 objcopy
来改变<$
So, use objcopy
to change the visibility of clash
in one (or both, if you like!) of the objects:
$ objcopy --localize-symbol=clash bar.o bar2.o
$
现在,您可以成功地与修改的对象链接 - 并且该程序的行为应该如此:
Now you can link successfully with the modified object - and the program behaves as it should:
$ gcc -o test main.o foo.o bar2.o
$ ./test
foo: Hello
bar: world
$
这篇关于如何避开“多个定义的符号”在与gcc链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!