A C program that calls sqrt compiles each .c file without errors, but the build fails with "undefined reference to `sqrt'". Which stage reported the error, and what is the usual fix on Linux?
AThe preprocessor; add #include <math.h>
BThe compiler's type checker; cast the argument to double
CThe linker; link the math library, for example by adding -lm
DThe loader; run the program with administrator rights
Compilation needs only the declaration from math.h. The linker must then find the actual definition of sqrt. On many Linux systems it lives in the separate math library, libm, which is linked with -lm. An undefined reference means the linker found a use with no matching definition.
Question 2 Multiple Choice
What does relocation do during linking?
AIt moves source files into the same folder
BIt assigns run-time addresses to code and data sections and patches each reference so it points to the correct final address
CIt deletes unused functions from the source code
DIt moves the program from disk into memory at run time
Each object file is generated as if its sections started at address zero. The linker merges sections, picks their final addresses, and uses the relocation entries in each object file to fix every instruction or data word that refers to a symbol. Copying the program into memory is the loader's job.
Question 3 True / False
When a program is dynamically linked against a shared library, the library's machine code is copied into the program's executable file at link time.
TTrue
FFalse
Answer: False
With dynamic linking, the executable records only which shared libraries it needs and which symbols it uses. The dynamic linker maps the library into the process at load or run time. Static linking is the case where library code is copied into the executable.
Question 4 Short Answer
Give two advantages of shared (dynamically linked) libraries over static libraries.
Think about your answer, then reveal below.
Model answer: First, one copy of the library's code can be mapped into the memory of many running programs, saving memory and disk space. Second, the library can be updated, for example with a security fix, and every program that uses it gets the fix without being relinked.
The trade-offs are a small cost at startup or first call to resolve symbols, and the risk that a program breaks if an incompatible library version is installed.