如何正确使用 -fPIC 和 -fPIE GCC 选项
我有这样的目录结构,
dir1
one.c
two.c
dir2
three_main.c
four.c
我需要在dir1
中创建一个共享库libdir1.so
。 并且可执行my_exe
在dir2
中的所有 c 文件中,以及libdir1.so
我正在创建< strong> .so 和可执行分为两个步骤。
.so step1: gcc -c -fPIC -g -O2 -pthread -o one.o one.c
gcc -c -fPIC -g -O2 -pthread -o two.o two.c
.so step2: gcc -shared -g -O2 -pthread -o libdir1.so one.o two.o
exe step1: gcc -c -fPIE -o three_main.o three_main.c
gcc -c -fPIE -o four.o four.c
exe step2: gcc -Wall -g -L -ldir1 -o my_exe three_main.o four.o
现在我的问题是...。
- 我应该使用 -fpic 和 -fpie
step1
或step2
或在两个都? - 我可以在创建 step2 中使用 -fpie 在创建 .so 文件中吗?
- 我可以在创建 step1 中使用 -fpic 在创建可执行文件中吗?
- 如何使用 relro 编译器选项来创建 .so 和可执行文件?
谢谢
I have a directory structure like this
dir1
one.c
two.c
dir2
three_main.c
four.c
I need to create a shared library libdir1.so
out of all c files in dir1
and an executable my_exe
out of all c files in dir2
along with the libdir1.so
I am creating the .so and the executable in two steps.
.so step1: gcc -c -fPIC -g -O2 -pthread -o one.o one.c
gcc -c -fPIC -g -O2 -pthread -o two.o two.c
.so step2: gcc -shared -g -O2 -pthread -o libdir1.so one.o two.o
exe step1: gcc -c -fPIE -o three_main.o three_main.c
gcc -c -fPIE -o four.o four.c
exe step2: gcc -Wall -g -L -ldir1 -o my_exe three_main.o four.o
Now my questions are....
- Should I use -fPIC and -fPIE in
step1
orstep2
or in both? - Can I use -fPIE in
step2
in creating the .so file? - Can I use -fPIC in
step1
in creating the executable? - How can I use RELRO compiler option in creating both .so and executable?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。您当前构建
.so
和二进制文件的方式是正确/最佳的。你可以,但你不应该:
-fPIE
是一个编译时选项,并且你只在第2步中链接。如果将-fPIE
传递给链接,它将被忽略。您可以,但这会在可执行文件中创建次优代码。
添加
-Wl,-z,relro
。是的:为了最大限度地强化,你应该这样做。没有
-z,now
的-Wl,-z,relro
并不是无效,而是不太有效。 详细信息。是的。
No. The way you currently build the
.so
and the binary is correct / optimal.You could, but you shouldn't:
-fPIE
is a compile-time option, and you are only linking in step2. If you pass-fPIE
to the link, it will be ignored.You could, but this will create sub-optimal code in the executable.
Add
-Wl,-z,relro
.Yes: for maximum hardening, you should.
-Wl,-z,relro
without-z,now
is not ineffective, but it is less effective. Details.Yes.