Linker 带有动态链接的静默复制符号错误

Linker 带有动态链接的静默复制符号错误,linker,shared-libraries,Linker,Shared Libraries,我有以下C文件: 基础h: void g(); void h(); B.c: #include <stdio.h> #include <Base.h> void g() { printf("This is lib g\n"); h(); } void h() { printf("This is lib h\n"); } 现在我运行程序 $ LD_LIBRARY_PATH=. ./A 并获得: This is lib g This is A h Thi

我有以下C文件:

基础h:

void g();
void h();
B.c:

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

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

void h() {
  printf("This is lib h\n");
}
现在我运行程序

$ 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调用中解析错误消息

如果我把交流中的h重命名为h1

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

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

void main() {
  g();
  h1();
}
所以,在这种情况下,h的解和我预期的一样

要获取错误消息或将g中的调用解析为libBase中的h,我必须做什么

这不是我所期望的

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

这种行为有很多优点。例如:您可以
LD_PRELOAD
libtcmalloc.so
,突然所有
malloc
free
调用解析为
tcmalloc

在ELF系统上,可以使用
-Bsymbolic
链接器标志修改此行为(在通过GCC时使用
-Wl,-Bsymbolic
)。注意:
-b符号
与系统背道而驰,因此可能会产生许多意想不到的不良副作用

另见答案

This is lib g
This is A h
This is A h
#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