Difference between gcc -fpic and -fPIC

本文介绍了如何使用-fpic和-fPIC选项生成位置独立代码(PIC),适用于动态链接并避免全局偏移表大小限制。详细解释了不同目标机如386、m68k、m88k和SPARC等的支持情况。
-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
perating 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 16k on the m88k, 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, m88k, 
and the SPARC.
Position-independent code requires special support, and therefore works only on certain machines.
---

### GCC -fPIC 选项的作用及使用场景 #### 1. **-fPIC 的定义** `-fPIC` 是 GNU 编译器集合(GCC)中的一个重要选项,其主要功能是生成与位置无关的代码(Position-Independent Code, PIC)。这种类型的代码能够在加载到内存的不同地址时仍然正常运行[^1]。 #### 2. **-fPIC 的作用** 当编译程序时指定 `-fPIC` 选项,GCC 将会生成适合用于共享库(Shared Libraries)的目标文件。这些目标文件的特点是可以被映射到任意虚拟地址空间而无需修改指令指针或数据引用的位置[^4]。具体来说: - 它允许操作系统在加载共享库时将其放置在可用的内存区域中,而不必重新定位整个二进制文件。 - 这种灵活性对于现代操作系统的动态链接机制至关重要,尤其是在 Linux 和类 Unix 系统中创建 `.so` 文件时必不可少[^3]。 #### 3. **适用场景** -fPIC 主要应用于以下几种情况: - 创建共享对象(Shared Objects),即动态链接库(Dynamic Link Libraries),例如 `.so` 文件(Linux/Unix 平台上的共享库扩展名)或者 `.dll` 文件(Windows 平台上类似的共享库形式)。 - 当开发人员希望减少应用程序的整体大小并提高性能时,通过利用已有的共享库来实现资源复用[^2]。 #### 4. **注意事项** 尽管 -fPIC 对于构建共享库非常有用,但在某些特定情况下可能并不必要甚至不推荐使用它。例如,在嵌入式系统或其他受限环境中,由于硬件架构的原因可能导致无法完全支持真正的 PIC;此时可以考虑替代方案如静态链接等方式代替[^3]。 下面是一个简单的例子展示如何正确地应用此标志来建立一个基本的共享库: ```bash # 假设有源码 file.c 需要编译成共享库 libfile.so gcc -c -fPIC file.c -o file.o # 使用 -fPIC 参数编译为目标文件 gcc -shared -o libfile.so file.o # 把目标文件组合成为共享库 ``` 以上命令序列展示了标准流程:先单独编译各模块为带 PIC 属性的对象文件,再把这些对象文件连接起来形成最终产物 —— 共享库 `libfile.so`. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值