编译GCC时是否还需要使用-fPIC? [英] Does one still need to use -fPIC when compiling with GCC?

查看:1223
本文介绍了编译GCC时是否还需要使用-fPIC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在gcc目标机器上,当想要编译共享库时,需要指定-fpic或-fPIC来使事情正确工作。这是因为默认情况下使用了绝对地址,它适用于完全控制自己地址空间的可执行文件,而不是共享库,可以在可执行文件的地址空间中的任何地方加载。

On gcc target machines, when one wanted to compile a shared library, one would need to specify -fpic or -fPIC to get things to work correcly. This is because by default absolute addressing was used, which is suitable for executable that have full control of their own address space, but not shared libraries, which could be loaded anywhere in an executable's address space.

然而现代内核现在正在实现地址空间随机化,许多现代体系结构都支持PC相对寻址。这一切似乎使绝对寻址无法使用(地址空间随机化)或不需要(PC相对寻址)。

However modern kernels are now implementing address space randomization and many modern architectures support PC relative addressing. This all seems to make the absolute addressing either unusable (address space randomization) or unneeded (PC relative addressing).

我也注意到clang没有-fPIC选项,这使得我不再需要它。

I have also notices that clang does not have a -fPIC option which makes me thing that it is no longer necessary.

因此-fpic现在是多余的,或者需要生成单独的.o文件,一个用于静态库的使用,还有一个用于共享库的使用?

So is -fpic now redundant or does one need to generate separate .o files, one for static library use, and one for shared library use?

推荐答案

您仍然需要使用-fPIC进行编译。这个问题不能用pc相对寻址解决。问题是你如何解决外部符号。在一个动态链接的程序中,解析遵循不同的规则,特别是随着地址空间随机化,它不能在链接时解决。

You still need to compile with -fPIC. The problem isn't solvable with pc-relative addressing. The problem is how you resolve external symbols. In a dynamically linked program the resolution follows different rules and especially with adress space randomization it can't be resolved during link time.

而clang的确只有-fPIC标志就像gcc。

And clang does have the -fPIC flag just like gcc.

$ cat > foo.c
void foo(void);
void bar(void) { foo(); }
$ gcc -S foo.c && grep call.*foo foo.s
    call    foo
$ gcc -fPIC -S foo.c && grep call.*foo foo.s
    call    foo@PLT
$ clang -S foo.c && grep call.*foo foo.s
    callq   foo
$ clang -fPIC -S foo.c && grep call.*foo foo.s
    callq   foo@PLT
$

这篇关于编译GCC时是否还需要使用-fPIC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆