c++gccfpic

GCC -fPIC option


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.