Order of Linkage

I have two questions:

1_ Does the linking process start from the object file containing main? I fully understand what compiling and linking are for, and what their outputs are, I'm just curious about the order in which things get done? How can the starting point be recognized for the linker to make the output binary?

2_ Also I wonder how it jumps from one object file to another in cases that there are references? I mean there are a lot of possible permutations in each step! Does it check all the other object files each time?

(Sorry for English if anythings was ambiguous, please tell me and I'll rephrase it.)
Does the linking process start from the object file containing main?

You can link files that don't contain main.


Order of linking is up to whoever wrote the linker.

Static linking using GCC:

The linker examines object files and library files in the order they're given on the command line, from left to right.

When it encounters an object file, it makes a note of everything exported and everything needed.

When it encounters a library file, it examines each object inside that library in turn and *only* if that object has something that is on the needed list does it add all that objects exports to the list of everything exported. If that object doesn't have anything on the needed list, it is skipped. However, if any one object file in that library does get used, then the linker cycles back over all the object files again; so object files can get multiple chances to get their symbols exported.

There are some finer details here, but basically it's possible for objects inside libraries to get ignored if, at the point the linker is looking at them, it doesn't need them. If something *later* does need it, the linker (by default) doesn't go back. This is why linking order in static linking makes a difference.

Other linker and dynamic linking, I couldn't tell you; I only know exactly how static linking on GCC works because of experience paying close attention to the link order sometimes.

Last edited on
> How can the starting point be recognized for the linker to make the output binary?

The linker gets this information from a command line option used to invoke the linker.

For, example, GNU: -Wl,-eentry my_prohram_start_function -nostartfiles
Microsoft: -entry: my_prohram_start_function

If this option this not specified, a reasonable default is provided (GNU: _start, Microsoft: mainCRTStartup etc.). Using this default is required for programs which use the standard library; it does whatever is required to initialise the run time library, parses command line arguments and then calls main()


> Does it check all the other object files each time?

Typically, a lookup table which maps symbols to offsets in the object files is created, and this lookup table is updated when a new object file is pulled in to link process.
Last edited on
Thanks a lot.
Topic archived. No new replies allowed.