【问题标题】:Silent duplicate symbol error with dynamic linking动态链接的静默重复符号错误
【发布时间】:2012-10-25 22:39:53
【问题描述】:

我有以下 C 文件:

Base.h:

void g();
void h();

Base.c:

#include <stdio.h>
#include <Base.h>

void g() {
  printf("This is lib g\n");
  h();
}

void h() {
  printf("This is lib h\n");
}

交流:

#include <stdio.h>
#include <Base.h>

void h() {
  printf("This is A h\n");
}

void main() {
  g();
  h();
}

我编译链接如下:

$ gcc -c -fPIC -o Base.o -I. Base.c
$ gcc -shared -o libBase.so Base.o
$ gcc -c -o A.o A.c
$ gcc -o A A.o -lBase -L.

现在我运行程序

$ LD_LIBRARY_PATH=. ./A

并获得:

This is lib g
This is A h
This is A h

也就是说,libBase 中对 h 的调用由 A.o. 的 h 解决。这不是我所期望的。我希望动态链接器使用 libBase 中的 h 解决对 libBase 中 h 的调用,或者在第四个 gcc 调用中出现错误消息。

如果我将 A.c 中的 h 重命名为 h1

#include <stdio.h>
#include <Base.h>

void h1() {
  printf("This is A h1\n");
}

void main() {
  g();
  h1();
}

我得到

This is lib g
This is lib h
This is A h1

因此,在这种情况下,h 按我的预期解决了。

我必须做什么才能获得错误消息或将 g 中的调用解析为 libBase 中的 h?

【问题讨论】:

    标签: linker shared-libraries


    【解决方案1】:

    这不是我所期望的。

    你的期望是错误的。这是大多数 UNIX 系统上的共享库的工作方式:加载器只需沿着已加载库的列表向下移动,并尝试找到给定的符号。第一个定义符号“wins”的库。

    这种行为有很多优点。一个例子:你可以LD_PRELOADlibtcmalloc.so,突然所有mallocfree调用都解析为tcmalloc

    在 ELF 系统上,您可以使用 -Bsymbolic 链接器标志修改此行为(通过 GCC 传递时使用 -Wl,-Bsymbolic)。当心:-Bsymbolic 会“违背系统”,因此您可能会得到许多意想不到的不良副作用。

    另请参阅this 答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多