首页 > 解决方案 > 为什么我的共享对象在没有 -fPIC 的情况下无法编译

问题描述

我写了一个简单的共享库,其中包含 stdio.h 中标准输出的用法。

#include <stdio.h>

...
  fflush(stdout);
...

在我使用以下命令添加 fflush(stdout) 之前没有编译问题

$gcc -shared -o a.so a.c 

但是在添加 fflush(stdout) 之后,编译器会抱怨:

/usr/bin/ld: /tmp/ccK4npwc.o: relocation R_X86_64_PC32 against symbol `stdout@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: bad value
collect2: error: ld returned 1 exit status

有人可以尽可能详细地解释这背后的理由吗?为什么这里必须是 -fPIC ?

编辑:一些评论建议我在 PIC 上阅读,但这缺少我的问题。我的问题是为什么我需要这个程序的 PIC。在我的程序中,我还使用了来自 libc 的 puts。我可以在没有 -fPIC 的情况下很好地编译它。但是为什么 stdout 变量需要 -fPIC 呢?

标签: cgccshared-librariesfpic

解决方案


推荐阅读