Symbols: nm, objdump & readelf
A symbol is a name with an address: a function, a global variable, a section label. Every object file carries a symbol table listing the symbols it defines and the ones it needs. Almost every link error, and most "works on my machine" library problems, can be diagnosed by reading symbol tables. Three binutils tools do that: nm (quick list), objdump (disassembly and headers) and readelf (everything ELF, in detail).
nm: what an object defines and needs
mkdir -p sym && cd sym
cat > shapes.c <<'SRC'
#include <stdio.h>
int shape_count = 3; /* initialised global */
int last_area; /* zero-initialised global */
const double PI = 3.14159; /* read-only global */
static int calls; /* file-local */
static double square(double x) { return x * x; }
double circle_area(double r) {
calls++;
last_area = (int)(PI * square(r));
printf("area %d\n", last_area);
return PI * square(r);
}
SRC
gcc -c -O0 shapes.c
nm shapes.o0000000000000000 R PI
0000000000000004 b calls
0000000000000018 T circle_area
0000000000000000 B last_area
U printf
0000000000000000 D shape_count
0000000000000000 t square
The letter is the symbol type; uppercase means global (visible to other objects), lowercase means local:
| Letter | Meaning | In this file |
|---|---|---|
T / t |
code in .text |
circle_area (global), square (static) |
D / d |
initialised data | shape_count |
B / b |
zero-initialised data (.bss) |
last_area, calls |
R / r |
read-only data | PI |
U |
undefined: needed from somewhere else | printf |
Things to notice:
staticfunctions and variables are local (t,b). The linker never matches them against other files, so two files can each have astatic int callswithout conflict. Making helpersstaticis the cheapest way to avoid symbol clashes.printfisU: this object needs it, and the linker must find it in another input (here, the C library).- Useful options:
nm -u(only undefined),nm --defined-only,nm -g(only globals),nm -C(demangle C++).
C++ names are mangled
C++ allows overloading, so area(double) and area(int) need different symbol names. The compiler encodes the parameter types into the name (name mangling). nm -C (or the c++filt tool) decodes them:
mkdir -p sym && cd sym
cat > geo.cpp <<'SRC'
namespace geo {
double area(double r) { return 3.14159 * r * r; }
int area(int w, int h) { return w * h; }
}
extern "C" int c_area(int w, int h) { return w * h; }
SRC
g++ -c geo.cpp
nm geo.o
echo "--- demangled"
nm -C geo.o0000000000000000 T _ZN3geo4areaEd
0000000000000025 T _ZN3geo4areaEii
000000000000003c T c_area
--- demangled
0000000000000000 T geo::area(double)
0000000000000025 T geo::area(int, int)
000000000000003c T c_area
extern "C" turns mangling off, which is how C++ libraries export functions that C code (and other languages' foreign-function interfaces) can call. A classic link error, undefined reference to 'foo(int)' when the library actually defines plain foo, means a C header was included in C++ without extern "C".
readelf and objdump: the same table, more detail
readelf -s prints the full symbol table with size, binding and visibility. objdump -t shows the same data in BSD style:
mkdir -p sym && cd sym
cat > counter.c <<'SRC'
static int hidden_total;
int visible_total;
int bump(int by) { hidden_total += by; visible_total += by; return visible_total; }
SRC
gcc -c counter.c
readelf -s counter.o | grep -E 'Num:|total|bump'
echo "--- objdump -t"
objdump -t counter.o | grep -E 'total|bump' Num: Value Size Type Bind Vis Ndx Name
4: 0000000000000004 4 OBJECT LOCAL DEFAULT 4 hidden_total
5: 0000000000000000 4 OBJECT GLOBAL DEFAULT 4 visible_total
6: 0000000000000000 53 FUNC GLOBAL DEFAULT 1 bump
--- objdump -t
0000000000000004 l O .bss 0000000000000004 hidden_total
0000000000000000 g O .bss 0000000000000004 visible_total
0000000000000000 g F .text 0000000000000035 bump
Bind is LOCAL or GLOBAL (or WEAK, below), Ndx is the section the symbol lives in (UND for undefined), Size is in bytes. objdump -t says the same with flags: l local, g global, F function, O object.
Weak symbols
A weak definition is a default that a normal (strong) definition elsewhere silently overrides. Libraries use it for hooks that applications may replace:
mkdir -p sym && cd sym
cat > lib.c <<'SRC'
#include <stdio.h>
__attribute__((weak)) const char *app_name(void) { return "unnamed app"; }
void banner(void) { printf("Starting %s\n", app_name()); }
SRC
cat > main.c <<'SRC'
void banner(void);
int main(void) { banner(); return 0; }
SRC
cat > name.c <<'SRC'
const char *app_name(void) { return "tad-demo"; }
SRC
gcc -c lib.c main.c name.c
nm lib.o | grep app_name
gcc lib.o main.o -o default && ./default
gcc lib.o main.o name.o -o custom && ./custom0000000000000000 W app_name
Starting unnamed app
Starting tad-demo
W marks a weak symbol. Without name.o the weak default is used; with it, the strong definition wins and no "multiple definition" error is reported.
Model: a symbol resolver
The linker's first pass is a bookkeeping exercise over symbol tables. This model applies the rules: one strong definition per global, weak loses to strong, any remaining undefined symbol is an error:
const objects = {
"main.o": { defines: { main: "strong" }, needs: ["banner", "config_path"] },
"lib.o": { defines: { banner: "strong", app_name: "weak" }, needs: ["app_name", "printf"] },
"name.o": { defines: { app_name: "strong" }, needs: [] },
"old.o": { defines: { banner: "strong" }, needs: [] }, // a stale copy of lib.c
"libc.so": { defines: { printf: "strong", puts: "strong" }, needs: [] },
};
const chosen = {}, errors = [];
for (const [file, obj] of Object.entries(objects)) {
for (const [sym, kind] of Object.entries(obj.defines)) {
const prev = chosen[sym];
if (!prev || (prev.kind === "weak" && kind === "strong")) chosen[sym] = { file, kind };
else if (prev.kind === "strong" && kind === "strong") errors.push(`multiple definition of '${sym}' (${prev.file}, ${file})`);
}
}
for (const [file, obj] of Object.entries(objects))
for (const sym of obj.needs)
if (!chosen[sym]) errors.push(`${file}: undefined reference to '${sym}'`);
for (const [sym, { file, kind }] of Object.entries(chosen).sort()) console.log(`${sym.padEnd(9)} <- ${file} (${kind})`);
for (const e of errors) console.log("error:", e);app_name <- name.o (strong)
banner <- lib.o (strong)
main <- main.o (strong)
printf <- libc.so (strong)
puts <- libc.so (strong)
error: multiple definition of 'banner' (lib.o, old.o)
error: main.o: undefined reference to 'config_path'
The two error kinds in the output, "undefined reference" and "multiple definition", are the two most common link errors. The next lesson produces both with the real linker.
Test yourself
In nm output, what does U printf mean?
printfis unusedprintfis used but not defined in this object; another input must provide itprintfis a user functionprintfis in the uninitialised data section
Why can two .c files both define static int calls; without a link error?
- The linker merges them
staticmakes the symbol local (b), so it is never matched across files- The second one is ignored
- It does cause an error
What does extern "C" change for a C++ function?
- It makes it faster
- It turns off name mangling, so the symbol is the plain C name
- It makes it static
- It moves it to a shared library