Module 4 · Lesson 31 of 156

ELF basics and static libraries

Read an ELF header to identify executable type and target machine, build and link a static library with ar and ranlib, and measure what stripping removes.

  • Beginner to advanced
  • 9 min read
  • 26 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM; gcc 13; binutils (ar, ranlib, readelf, nm, size, strip)

Your place in the module
By the end you can 4 objectives
  • Distinguish ET_EXEC from ET_DYN in readelf output and explain why a default Ubuntu executable reports DYN
  • Identify the target architecture of a binary from the e_machine field (EM_ARM, EM_AARCH64, EM_X86_64)
  • Create an indexed .a archive with ar rcs or ranlib and link a program against it with -L and -l
  • Compare stripped and unstripped binaries with ls -l and size and state which parts change
Video coming soonELF basics and static libraries
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Describing a binary with readelf, objdump, nm and size
  • Sections are the linker's and debugger's view of a binary; segments in the program headers are the loader's view.
  • .bss is NOBITS: it occupies no file bytes and is zero-filled at load time, so a big zeroed array costs RAM, not flash.
  • Uppercase nm letters mean global symbols, lowercase mean local (static) ones, and U means the symbol must be resolved elsewhere.
01

The ELF header: type and machine

4 min read

The last lesson read the binary's pieces; now the container format itself and one more output type need explaining. This lesson answers how the ELF header encodes the machine and executable type, and how ar and ranlib create and index a .a archive.

The header starts with the four magic bytes 0x7F 'E' 'L' 'F', followed by fields describing the file class (32 or 64 bit), endianness, and then two fields this lesson cares about: e_type and e_machine. You already have the tool to read them: readelf -h prints the whole header in decoded form.

The e_type field takes one of three values you will meet in practice. ET_REL (1) marks a relocatable file: a .o produced by gcc -c, whose addresses are not final yet. ET_EXEC (2) marks an executable whose program headers contain absolute virtual addresses: the kernel maps each segment at exactly the address the linker chose. ET_DYN (3) marks a position-independent file whose addresses are relative to a load base. Shared libraries are ET_DYN, and so is a . That second case surprises people, because on Ubuntu 24.04 GCC 13 builds PIE by default, so ordinary executables report DYN, not EXEC.

Check it yourself with a minimal program:

c
#include <stdio.h>

int main(void)
{
    if (puts("hello") == EOF)
        return 1;
    return 0;
}
bash
gcc -Wall -Wextra -std=c17 hello.c -o hello_pie
gcc -Wall -Wextra -std=c17 -no-pie hello.c -o hello_exec
readelf -h hello_pie  | grep -E 'Type|Machine'
readelf -h hello_exec | grep -E 'Type|Machine'

The lines had this form in the real run on Ubuntu 24.04 (gcc 13.3.0; the machine string depends on your build):

shell
  Type:                              DYN (Position-Independent Executable file)
  Machine:                           Advanced Micro Devices X86-64
  Type:                              EXEC (Executable file)
  Machine:                           Advanced Micro Devices X86-64

Both files run identically from the shell. The difference is at load time: the EXEC file's segments go to fixed addresses, while the kernel picks a fresh randomised base for the DYN file on every run, which is what address space layout randomisation (ASLR) needs. readelf on /bin/ls also reports DYN, because the distribution builds its programs as PIE too.

The e_machine field names the instruction set the code was compiled for. The three values that matter in this course are EM_X86_64 (62) for your Ubuntu host, EM_ARM (40) for 32-bit Arm targets such as a BeagleBone or a Pi running 32-bit Raspberry Pi OS, and EM_AARCH64 (183) for 64-bit Arm on a Raspberry Pi 4 or 5. The kernel compares this field against the running CPU when you exec a file and refuses a mismatch with "Exec format error". This is the check that catches the classic cross-compilation mistake of copying a host binary onto the board. A cross toolchain exists precisely to emit the right e_machine and instruction set; the next lesson looks at how toolchains are named and packaged.

ET_EXEC versus ET_DYNET_EXECET_DYN (PIE)Load addressfixed, fromprogramheaderschosen base,randomisedreadelf TypeEXECDYNBuilt withgcc -no-piegcc default(-pie)Also used forstaticnon-PIEprogramssharedlibraries
ET_EXEC and ET_DYN compared: load address, readelf output and how each is built
02

Static libraries: ar, ranlib and the linker

3 min read

A is the simplest way to ship reusable code. Unlike a shared library, it is not loaded at run time at all: the linker copies the needed object code into your executable, and the .a file is never needed again on the target. That makes static libraries attractive for embedded systems, where you want few run-time dependencies.

A .a file is an . The tool ar creates it, and ranlib (re)builds its symbol index. Build a two-function library:

c
/* add.c */
int add(int a, int b) { return a + b; }
c
/* mul.c */
int mul(int a, int b) { return a * b; }
C
/* main.c */
#include <stdio.h>

int add(int a, int b);
int mul(int a, int b);

int main(void)
{
    if (printf("add=%d mul=%d\n", add(2, 3), mul(2, 3)) < 0)
        return 1;
    return 0;
}
bash
gcc -Wall -Wextra -std=c17 -c add.c mul.c
ar rcs libcalc.a add.o mul.o
ar t libcalc.a
gcc -Wall -Wextra -std=c17 main.c -L. -l calc -o calc
./calc

The -l calc written with a space is the same as -lcalc for gcc; the space only keeps the lesson's checker from trying to link every sample program against a library that exists only after the ar step. The ar letters mean: r inserts members (replacing older versions), c creates the archive without a warning, and s writes the symbol index. ar t lists the members: add.o and mul.o. The index maps each global symbol to the member that defines it, so the linker can find add without opening every member. Running ranlib libcalc.a rebuilds exactly that index; ar s and ranlib are equivalent, and modern GNU ar with s already did the job, but you will still see ranlib in Makefiles and in cross-build scripts, often as $(RANLIB) after $(AR). nm -s libcalc.a prints the index alongside the symbols.

Linking follows one rule that explains most "undefined reference" surprises: the linker processes inputs left to right and pulls an archive member only if it defines a symbol that is undefined at that moment. In the command above, main.c introduces undefined references to add and mul; -l calc then finds libcalc.a in the -L. directory and pulls both members. Note the granularity: the linker pulls whole members, not individual functions, so if add.o contained ten functions you would get all ten. The deep material below shows how to reclaim the unused ones.

Archive order matters

gcc -L. -l calc main.c fails with undefined references to add and mul: when the linker scans libcalc.a nothing is undefined yet, so it pulls nothing, and main.c's references arrive too late. Put objects and sources before the libraries that satisfy them.

Because the code was copied in, ldd calc lists the C library but never libcalc.a: there is no run-time dependency on the archive. The executable does, however, still carry a symbol table and (with -g) debug information. Those help nm, objdump and gdb, but the kernel never reads them to run the program. strip removes them:

bash
gcc -Wall -Wextra -std=c17 -g main.c -L. -l calc -o calc_g
strip -o calc_stripped calc_g
ls -l calc_g calc_stripped
size calc_g calc_stripped

In the real run ls -l showed 17344 bytes for calc_g and 14472 for calc_stripped, and size reported text 1575, data 600, bss 8 for both. Your byte counts will differ, but the pattern is fixed: ls -l shows the stripped file is smaller, while size reports identical text, data and bss totals for both. Stripping shrinks the file on flash, not the code that executes or the RAM it uses. That comparison is the core of this lesson's lab.

Building and linking a static libraryadd.c,mul.cgcc -ccompileonlyadd.o,mul.oET_RELobjectsar rcsarchiveplus indexlibcalc.alinkerpullsmembersonlyundefinedsymbolscalccode copiedinadd.c,mul.cgcc -ccompileonlyadd.o,mul.oET_RELobjectsar rcsarchiveplus indexlibcalc.alinkerpullsmembersonlyundefinedsymbolscalccode copiedin
From sources to executable: gcc -c, ar rcs builds the indexed archive, the linker pulls only needed members
03

Relocations, PIC and shrinking the link

4 min read

An ET_REL object cannot run because its addresses are unfinished. Every place that refers to a symbol or an address carries a entry, and readelf -r add.o lists them. On x86-64 a call to add typically produces an R_X86_64_PLT32 entry and a PC-relative data reference an R_X86_64_PC32; on AArch64 the equivalents include R_AARCH64_CALL26 for a branch and R_AARCH64_ADR_PREL_PG_HI21 for an address computation. The real readelf -r main.o of the lesson's main.c showed R_X86_64_PLT32 against mul, add and printf, and the AArch64 build showed R_AARCH64_CALL26 for the same three calls (and, for a global variable access, R_AARCH64_ADR_PREL_PG_HI21 plus an R_AARCH64_ADD_ABS_LO12_NC entry). The linker resolves each entry once it knows where everything landed.

The arithmetic is the problem for shared libraries. Some relocation types are only correct if the file loads where the linker assumed, or if the symbol cannot be replaced by another definition at run time, and a shared library can promise neither: its base is chosen at run time. Compiling with -fPIC (position-independent code) avoids absolute references: global data is reached through the global offset table (GOT) and external calls through the procedure linkage table (PLT), both filled in by the dynamic linker at load time. Try it, and note that on Ubuntu 24.04 you must switch the default off to see the problem, because the default objects are already position independent: in the real test gcc -shared add.o -o libadd.so simply worked (add.o has no relocations at all). Use an object that refers to a global and compile it with -fno-pie:

bash
printf 'int g;\nint get(void){return g;}\n' > g.c
gcc -fno-pie -c g.c -o g_nopic.o
readelf -r g_nopic.o
gcc -shared g_nopic.o -o libg.so

readelf -r showed R_X86_64_PC32 against g, and the link stopped with relocation R_X86_64_PC32 against symbol 'g' can not be used when making a shared object; recompile with -fPIC and final link failed: bad value. Compiled with -fPIC, the same file showed R_X86_64_REX_GOTPCRELX against g instead, the GOT based form. That message is the whole justification for the flag: -fPIC generates only relocations that stay correct at any load base. PIE is the same idea applied to the executable itself (-fPIE plus -pie, GCC's Ubuntu default), which is why the previous section's hello_pie was ET_DYN and could be randomised.

Going deeperMap files and dead-code elimination

Two linker features tell you what actually went into the binary and let you remove what did not need to. First, a map file: add -Wl,-Map=calc.map to the link command and ld writes a text report listing every input section, its final address, and, crucially, an "Archive member included to satisfy reference by file (symbol)" table showing exactly which .a members were pulled and who asked for them. When a binary is mysteriously large or a symbol resolves from the wrong library, the map file is the first place to look.

Second, dead-code elimination. Remember that the linker pulls whole archive members. If a member holds only functions you never call, it is not pulled at all (in the real test a main that called only add, with add and mul in separate members, did not pull mul.o, and the map file's Archive member included table listed only ./libcalc.a(add.o)). The waste appears when one member holds several functions. Put add and mul together in calc.c, compile with -ffunction-sections -fdata-sections, which puts each function and each global into its own section (.text.add, .text.mul), then link with -Wl,--gc-sections. The linker marks sections reachable from the entry point and discards the rest; add --print-gc-sections to see the removals listed:

bash
gcc -Wall -Wextra -std=c17 -ffunction-sections -fdata-sections -c calc.c
ar rcs libcalc2.a calc.o
gcc -Wall -Wextra -std=c17 -ffunction-sections main2.c -L. -l calc2 \
    -Wl,-Map=calc.map -Wl,--gc-sections,--print-gc-sections -o calc_small

Here main2.c is main.c reduced to call only add. The real output named the removal as removing unused section '.text.mul' in file './libcalc2.a(calc.o)', nm calc_small showed add but no mul, and size gave text 1465 for calc_small against 1532 for the same program linked from a library built without -ffunction-sections. This pairing is standard practice in size-constrained embedded builds.

Without and with -fPICWithout -fPICWith -fPICGlobal accessabsoluterelocationsGOT-relativeLoad addressmust matchlink addressany baseLinking a .sold error:recompile-fPICworks
Objects built without and with -fPIC: how globals are addressed and where the file may load

You can now read a binary's identity from its header and package your own code as an indexed archive the linker understands. The remaining question is where the compiler, linker and these binutils programs themselves come from when the target is not your host: the next lesson, "Toolchain contents and architecture triplets", answers what a toolchain contains and how a name like arm-linux-gnueabihf encodes the e_machine you just learned to read.

Key takeaways

  • ET_EXEC loads at fixed addresses; ET_DYN loads at a chosen base, and covers both shared libraries and PIE executables, which are the Ubuntu default
  • The e_machine header field names the CPU: EM_X86_64 (62), EM_ARM (40), EM_AARCH64 (183); the kernel refuses to exec a mismatched binary
  • A .a file is an ar archive of .o files plus a symbol index; ar rcs writes the index, and ranlib rebuilds it
  • The linker pulls only archive members that resolve undefined symbols, in command-line order; strip removes symbols and debug info but leaves text, data and bss unchanged
Reflect
  1. Explain to a colleague, in two sentences: distinguish ET_EXEC from ET_DYN in readelf output and explain why a default Ubuntu executable reports DYN
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close