What, if any, are the implications of compiling objects with gcc -fPIC flag if they get used in executables?
Asked Answered
L

1

12

I am putting together a makefile for a project i am working on. I have an executable and a shared library in the project. Both use some of the same source files which get compiled separately into object files. To be able to use these objects in the shared library I need to use the -fPIC (position independent code) flag in gcc. Are there any implications of compiling objects with -fPIC that get used in a executable?

Ludly answered 22/7, 2009 at 14:16 Comment(2)
Looks like GCC7 now requires everything compiled with -fPIC. At least i get n error and found this question in the search of why i do get the error ?Brunabrunch
@Brunabrunch No, it does not require it in general. Are you mixing objects compiled with and without -fPIC?Special
S
9

Compiling position-independent code when not necessary is a performance drag on some platforms (most notably, the register-starved x86 architecture, because PIC takes away a register that can be used more freely when non-PIC), but there should be no detrimental effects otherwise.

Going further, it is even possible to create a position-independent executable (-fPIE) built out of only position-independent code.

That being said, libtool can automatically produce both PIC and non-PIC objects for each source file you compile, and it should be easy to do the same even in a build system without libtool integration.

Special answered 22/7, 2009 at 20:38 Comment(2)
No PIC does not take away a register on x86. This CPU does not have position indirect code and therefore always adds an indirection to the data/functions. You can forget about -fPIC totally on x86 because if you don't specify it you get fast code and the linker duplicates the code segment for each executable.Brunabrunch
@Brunabrunch On x86-32, depending on the compiler, PIC does take away a register. GCC prior to 5.0 reserves %ebx, making it not available for general use. gcc.gnu.org/bugzilla/show_bug.cgi?id=54232Special

© 2022 - 2024 — McMap. All rights reserved.