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

时间:2009-06-08 20:54:37

标签: c++ c gcc fpic

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

3 个答案:

答案 0 :(得分:54)

PIC代表职位独立代码

并引用man gcc

  

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

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

答案 1 :(得分:26)

f是用于“控制所使用的接口约定”的选项的gcc前缀        在代码生成“

PIC代表“位置独立代码”,它是m68K和SPARC fpic的特化。

编辑:在阅读document referenced by 0x6adb015的第11页和coryan的评论后,我做了一些更改:

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

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

毋庸置疑,我们几乎总是使用-fpic / PIC。

答案 2 :(得分:15)

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.