0

The man page of gcc has a section to describe position of -l option:

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

The question is:

If linker search & process file list in order, then shouldn't the command specify -l option before any source code & object file, instead of after them, so that the library could be used for all object files.

Eric
  • 22,183
  • 20
  • 145
  • 196
  • 1
    The linker only searches the library for missing symbols in objects and libraries already seen (before on the command line). – Marc Glisse Dec 08 '15 at 06:26
  • @MarcGlisse I see, didn't know it works in that way. Yeah, it makes sense, so that it don't need to load symbols not occurred in previous object files. – Eric Dec 08 '15 at 06:29
  • 1
    No. Object files first, libraries afterwards. That way, the linker knows which symbols the object files need from the libraries, and can make sure the correct libraries are loaded. Linkers only include libraries that provide references to symbols that are already known to be part of the program. – Jonathan Leffler Dec 08 '15 at 06:32
  • Possible duplicate of [Why does the order of '-l' option in gcc matter?](https://stackoverflow.com/q/11893996/608639) – jww Dec 11 '18 at 02:37

1 Answers1

2

The linker simply resolve external references in the order they are presented on the command line.

Taking the example in your quote, foo.o -lz bar.o: If foo.o uses functions in the z library then those are resolved when the linker loads the z library. However it doesn't really cache those entries, and once the external references have been resolved using the z library, the linker forgets about them. Now when bar.o comes along and attempts to use functions from the z library, those will not be resolved since the linker will not read the z library again.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621