views:

402

answers:

1

I've always been confused about how the linker works, and it's a difficult subject to search for.

To demonstrate my question and to provide a framework for an answer, I'll put down what I know (or think I know) so far. I may be very wrong. :)

First, each .cpp file is built into an intermediate file (.o for Posix/ELF and .obj for Win/PE I believe). This intermediate file contains all the symbols defined by the .cpp it was built from and has instructions for what external links it needs to be properly resolved. As an extension to this, Posix systems let you combine the .o files into a .a file (Which doesn't seem to do anything more than combine? What command does this?). Is .lib the Win/PE equivalent of the Posix .a file?

Next, the intermediate files are linked together, external dependencies resolved, and you have your executable. Am I missing any steps?

Thanks!

+1  A: 

Here's a few pieces of the puzzle:

  • ar(1) is used to create .a files. They are similar to tar(1) or zip files (possibly with a index to look up an object file by symbol name)
  • The linker copies together the sections of object files (text, data, bss). For GNU ld, the precise copying of sections can be controlled with a linker script (e.g. copy all sections from .o files containing "text" in their names into a single text section)
  • The linker also does relocations: patching instructions (jump and data load) with the respective target addresses, once the value of a symbol is known. In some cases, this can't be done at link time, so the linker copies/adjusts the relocation records from the .o files into the final executable.
  • the windows .lib serves two purposes: a static library (.lib) is similar to .a libraries. An import library (.lib) does not contain the actual code, but only symbol lists. The linker can resolve symbols from the import library, but then knows it needs to put a reference to the corresponding .dll into the executable. On Unix/ELF, the .so file has both the code and the symbol table.
Martin v. Löwis
Excellent, that answers all my questions. Thanks! :)
Nayruden