「操作系统」:Linker Use static Libraries

While static libraries are useful and essential tools, they are also a source of confusion to programmers because of the way the Unix linker uses them to resolve external references.During the symbol resolution phase, the linker scans the relocatable object files and archives left to right in the same requential order that they appear on the complier driver's command line.(The driver automatically translates any .c files on the command line into .o files) During this scan, the linker maintains a set E of relocatable object files that will be merged to form the executable, a set U of unresolved symbols (i.e., symbols referred to , but not yet defined), and a set D of unresolved symbols (i.e., symbols referred to , but not ye defined), and a set D of symbols that have been defined in previous input files. Initially, E, U, and D are empty.

    For each input file f on the command line, the linker determines if f is an object file or an archive. If f is an object file, the linker add f to E, updates U and D to reflect the symbol definitions and referrences in f, and proceeds to the next input file.

    if f is an archive, the linker attempts to match the unresolved symbols in U against the symbols defined by the members of the archive. If some archive member, m, defines a symbol that resolves a reference in U, then m is added to E, and the linker updates U and D to reflect the symbol definitions and referencces in m. This process iterates over the member object files in the archive until a fixed point is reached where U and D no longer change. At this point, any member object files not contained in E are simply discarded and the linker proceeds to the next input file.

    if U is nonempty when the linker finishes scanning the input files on the command line, it prints an error and terminates . Otherwise, it merges and relocates the object files in E to build the output executable file.

    Unfortunately, this algorithm can result in some baffling link-time errors because the ordering of libraries and object files on the command line is significant. If the library that defines a symbol appears on the command line before the object file that references that symbol, then the reference will not be resolved and linking will fail.

posted @ 2014-03-23 09:28  sangoly  阅读(204)  评论(0编辑  收藏  举报