Linkers, Loaders & Executables

With the GNU linker, writing a static library before the object file that uses it, as in "gcc -lmylib main.o", can cause undefined-reference errors. Why?

  1. AThe linker works left to right and does not extract functions not yet referenced when it reads the library
  2. BOnly one library may be written, and only at the end of the command
  3. CWriting the library first erases its contents
Show answer and explanation

Answer: A. The linker works left to right and does not extract functions not yet referenced when it reads the library

The GNU linker processes files in command-line order, and when it meets a static library it extracts only the objects that resolve references still undefined at that moment. If the library comes first, main.o's references do not exist yet, so nothing is extracted, and the linker does not go back after reading main.o. That is why libraries are normally written after the files that use them.

  • A. Correct. The order matters.
  • B. Several libraries may be given.
  • C. The library's contents are never erased.
Practice this topic Back to topic

More Linkers, Loaders & Executables questions

  1. Which describes position-independent code (PIC)?
  2. What is the role of the GOT (global offset table) used in shared libraries?
  3. When dynamic linking uses lazy binding through the PLT (procedure linkage table), which statement is correct?
  4. What is the role of the dynamic linker (such as ld.so) when a dynamically linked program starts on Linux?
  5. What is the purpose of ASLR (address space layout randomization)?