ld Command Cheat Sheet
ld is the GNU linker. It combines a number of object and archive files, relocates their data, and ties up symbol references to produce an executable or a shared library.
Note: ld is rarely run directly by users. It is usually invoked implicitly by gcc or g++. However, understanding its options is crucial for debugging linking errors.
Synopsis
ld [OPTIONS] OBJFILES...
Basic Usage
Linking Object Files manually
If you have main.o and utils.o:
ld -o myapp /usr/lib/crt1.o /usr/lib/crti.o main.o utils.o -lc /usr/lib/crtn.o
gcc handles including the C Runtime (crt) start/end files automatically. Invoking ld directly requires you to specify them manually.
Better way (via gcc wrapper):
gcc main.o utils.o -o myapp
ld behind the scenes).
Pass Options from GCC
To pass flags to ld via gcc, use -Wl,option:
gcc main.o -o myapp -Wl,-Map=output.map
Common Options
Specify Output (-o)
ld -o output_file content.o
Search Paths (-L)
Add directory to library search path.
ld -L/usr/local/lib -lmylib
Link against Library (-l)
Links against libNAME.so or libNAME.a.
ld -lmath # Looks for libmath.so or libmath.a
Advanced Options
Generate Map File (-Map)
Creates a diagnostic file showing exactly where symbols are mapped in memory.
ld -Map=linker.map ...
Runtime Library Search Path (-rpath)
Embeds a library path into the executable binary, so it can find .so files at runtime without setting LD_LIBRARY_PATH.
ld -rpath=/opt/myapp/lib ...
gcc -Wl,-rpath=/opt/myapp/lib ...
Shared Library Creation (-shared)
Create a shared object (.so).
ld -shared -o libutils.so utils.o
Strip Symbols (-s)
Remove all symbol information from the output file (reduces size, makes debugging impossible).
ld -s ...
Troubleshooting
"undefined reference to..."
The linker cannot find the definition of a function.
1. Check if you included the .o file or -l library.
2. Order matters! Put libraries after the objects that use them.
Wrong: ld -lm main.o
Right: ld main.o -lm
"multiple definition of..."
The same symbol is defined in two different object files.
Linker Scripts (-T)
ld is controlled by a Linker Script (.ld file). This controls memory layout (text, data, bss sections).
ld -T custom_layout.ld main.o
Notes
ld.so(Dynamic Linker) is different fromld.ldbuilds the binary;ld.soloads it at runtime.- Use
ld --verboseto see the default linker script.