为什么在Linux平台上,动态链接需要存在带有GCC的SO文件?

为什么在Linux平台上,动态链接需要存在带有GCC的SO文件?,gcc,linker,Gcc,Linker,考虑以下使用pthread的简单代码: #include<pthread.h> #include<stdio.h> #include <unistd.h> void *thread(void *ptr) { long type = (long) ptr; printf("value: %ld\n", type); return NULL; } int main() { pthread_t thread1; long value = 1;

考虑以下使用pthread的简单代码:

#include<pthread.h>
#include<stdio.h>
#include <unistd.h>

void *thread(void *ptr) {
  long type = (long) ptr;
  printf("value: %ld\n", type);
  return NULL;
}

int main() {
  pthread_t thread1;
  long value = 1;
  pthread_create(&thread1, NULL, *thread, (void*) value);
  pthread_join(thread1, NULL);
  return 0;
}
我知道我应该使用
gcc-o-thread-thread.c-lpthread
来完成这项工作。我的问题是为什么SO文件需要由
-lpthread
指定。我的猜测是,链接器需要在链接时知道所需SO文件的文件名,例如
libpthread.SO
,并将符号(
pthread\u create
pthread\u join
)和
pthread
库的文件名之间的映射添加到生成的程序
thread
。因此,当运行
thread
时,链接器可以找到SO文件,用于定义
pthread\u create
pthread\u join

我使用的是16.04.5 LTS 64位和GCC 8.1.0


我的猜测正确吗?

加载动态可执行文件时,动态链接器将加载所有引用的.so文件,然后根据所有引用的库解析所有外部符号。静态链接器只是验证是否可以在某个引用库中找到所有外部符号;为了知道它应该引用哪些库,可以使用-l


例如,如果您碰巧知道pthread函数已经在运行时libc(而不是编译时libc)中,您可以使用-Wl,--undefined这样的标志来告诉静态链接器忽略未定义的符号。在运行时,符号将在运行时库中找到

无法在我的系统或@MikeKinghan
cc-o thread thread.c上重现链接失败。c
适用于macOS上的
clang
/tmp/ccNBTPFM.o: In function `main':
thread.c:(.text+0x69): undefined reference to `pthread_create'
thread.c:(.text+0x7a): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status