7

Could somebody explain why I should be interested in compiling position-independent code, and also why should I avoid it?

0

3 Answers 3

5

Making code position-independent adds a layer of abstraction, which requires an additional lookup step at runtime for certain operations (usually pertaining to accessing variables with static storage).

So if you don't need it, don't use it!

There are specific situations where you must produce PIC (namely when creating run-time loadable code, such as a plug-in module or library), but the added flexibility comes at a price.

4

The gory details depend on how your loader works on on whether you are building a executable or a library, but there is a sense in which this is all a problem for the build system and the compiler, not for you.

If you really want to understand you need to consider where the code gets put in the address space before execution starts and what set of branching instructions your chip provides. Are branches relative or absolute? Is access to the data segment relative or absolute?

  • If branches are absolute, then the code must be loaded to a reliable address or it won't work. That's position dependent code. Many simple (or older) operating systems accommodate this by always loading a program to the same place.

  • Relative branches mean that the can be placed at any location in memory. That is position independent code.


Again, all you need to know is the recipe for invoking your compiler and linker on your platform.

1

PIC code usually has to be slightly larger because the compiler can't use instructions that encode relative address offsets. Without PIC, many addresses can be encoded with 16 or 8 bits relative to current PC. Sometimes in embedded systems, PIC is useful. For example if you want to have patch code that can run at various physical addresses.

2
  • so when in some C code there is AN_ATTRIBUTE with a precise memory address 0x84641 it's fair to say that this is an useful side of the PIC technique?
    – Ken
    Sep 15, 2012 at 18:44
  • Accessing things like memory mapped IO registers at fixed locations is a special case, and generally needs some trickery that makes it independent of the relocable/not-relocable distinction. However, that is a case where you do need to understand what is going on. Reading your compilers assembly output is often the best way to go. Sep 15, 2012 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.