TExcelTAD
Home › Build Fundamentals: From Source to Binary › Symbols: nm, objdump & readelf

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

bash · try it yourself
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.o
0000000000000000 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:

  • static functions and variables are local (t, b). The linker never matches them against other files, so two files can each have a static int calls without conflict. Making helpers static is the cheapest way to avoid symbol clashes.
  • printf is U: 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:

bash · try it yourself
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.o
0000000000000000 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:

bash · try it yourself
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:

bash · try it yourself
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 && ./custom
0000000000000000 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:

js · try it yourself
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?

  1. printf is unused
  2. printf is used but not defined in this object; another input must provide it
  3. printf is a user function
  4. printf is in the uninitialised data section

Why can two .c files both define static int calls; without a link error?

  1. The linker merges them
  2. static makes the symbol local (b), so it is never matched across files
  3. The second one is ignored
  4. It does cause an error

What does extern "C" change for a C++ function?

  1. It makes it faster
  2. It turns off name mangling, so the symbol is the plain C name
  3. It makes it static
  4. It moves it to a shared library