3

我有以下 C 文件:

基数.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 的调用是由 Ao 的 h 解决的,这不是我所期望的。我要么期望动态链接器使用 libBase 中的 h 解析对 libBase 中的 h 的调用,要么期望在第四个 gcc 调用中出现错误消息。

如果我将 Ac 中的 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?

4

1 回答 1

2

这不是我所期望的。

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

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

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

另请参阅答案。

于 2012-10-26T02:09:36.180 回答