-fPIC在构建共享库时意味着什么?

104 c c++ gcc fpic

我知道' -fPIC'选项与解决各个模块之间的地址和独立性有关,但我不确定它的真正含义.你可以解释吗?

sea*_*ley 58

PIC代表位置独立代码

并引述man gcc:

如果目标机器受支持,则发出与位置无关的代码,适用于动态链接并避免对全局偏移表的大小进行任何限制.此选项对m68k,PowerPC和SPARC产生影响.与位置无关的代码需要特殊支持,因此仅适用于某些机器.

在这些提到的体系结构上构建共享对象(*.so)时使用它.

  • fpic和fPIC之间存在差异.它们都做同样的事情,但fpic使用较短的相对偏移量.因此使用fpic进行编译可能会产生较小的文件.不幸的是,它并不总是按预期工作,所以使用fPIC.另请注意,并非所有处理器都支持较短的偏移,因此它可能没有区别. (17认同)
  • 'f'是gcc handeled命令行参数的一种宿醉(这是几年前的事情,他们已经改变了我最近没看过的这部分代码).但当时只允许在不同条件下使用某些字母或组合(定义命令行参数的语言非常复杂),因此使用'f'可以很容易地将其定义为命令行参数. (2认同)
  • 如果没有fPIC构建*.so会发生什么? (2认同)
  • @IsaA 我今天正在从源代码编译一个 c-api mysql 函数,但它无法构建,我得到了 `/usr/bin/ld: /tmp/cc7hXILq.o: relocation R_X86_64_32 against \`.rodata' 不能使用制作共享对象时;用 -fPIC` 重新编译,所以我添加了 fPIC 并构建了它。 (2认同)

Mar*_*ith 30

f是选项"控制接口约定在代码生成中使用的"在gcc前缀

PIC代表"位置无关的代码",它的一个专业化fpic的M68K和SPARC.

编辑:在阅读0x6adb015引用文档的第11页和coryan的评论后,我做了一些更改:

此选项仅对共享库有意义,并且您告诉操作系统您正在使用全局偏移表GOT.这意味着您的所有地址引用都与GOT相关,并且代码可以在多个进程中共享.

否则,如果没有此选项,加载程序将必须自行修改所有偏移量.

不用说,我们几乎总是使用-fpic/PIC.


Nik*_*sov 16

man gcc 说:

-fpic
  Generate position-independent code (PIC) suitable for use in a shared
  library, if supported for the target machine. Such code accesses all
  constant addresses through a global offset table (GOT). The dynamic
  loader resolves the GOT entries when the program starts (the dynamic
  loader is not part of GCC; it is part of the operating system). If
  the GOT size for the linked executable exceeds a machine-specific
  maximum size, you get an error message from the linker indicating
  that -fpic does not work; in that case, recompile with -fPIC instead.
  (These maximums are 8k on the SPARC and 32k on the m68k and RS/6000.
  The 386 has no such limit.)

  Position-independent code requires special support, and therefore
  works only on certain machines. For the 386, GCC supports PIC for
  System V but not for the Sun 386i. Code generated for the
  IBM RS/6000 is always position-independent.

-fPIC
  If supported for the target machine, emit position-independent code,
  suitable for dynamic linking and avoiding any limit on the size of
  the global offset table.  This option makes a difference on the m68k
  and the SPARC.

  Position-independent code requires special support, and therefore
  works only on certain machines.