HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

GCC -fPIC option

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fpicgccoption

Problem

I have read about GCC's Options for Code Generation Conventions, but could not understand what "Generate position-independent code (PIC)" does. Please give an example to explain me what does it mean.

Solution

Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.

E.g. jumps would be generated as relative rather than absolute.

Pseudo-assembly:

PIC: This would work whether the code was at address 100 or 1000

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP


Non-PIC: This will only work if the code is at address 100

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP


EDIT: In response to comment.

If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.

Code Snippets

100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP

Context

Stack Overflow Q#5311515, score: 738

Revisions (0)

No revisions yet.