TExcelTAD

Object Files (-c)

The assembler turns assembly text into an object file: real machine code, but not yet a program. An object file is the unit every C/C++ build system works with. make, Ninja and CMake spend most of their time deciding which .o files are stale and recompiling them; the linker then combines them. gcc -c runs every stage up to and including assembly, and stops.

Making object files

bash · try it yourself
mkdir -p obj && cd obj
cat > greet.c <<'SRC'
#include <stdio.h>
void greet(const char *who) {
    printf("Hello, %s!\n", who);
}
SRC
cat > main.c <<'SRC'
void greet(const char *who);
int main(void) {
    greet("builder");
    return 0;
}
SRC
gcc -c greet.c
gcc -c main.c
ls
file main.o
size main.o greet.o
greet.c
greet.o
main.c
main.o
main.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
   text	   data	    bss	    dec	    hex	filename
    126	      0	      0	    126	     7e	main.o
    146	      0	      0	    146	     92	greet.o
  • ELF (Executable and Linkable Format) is the object and executable format on Linux and most Unix systems. Windows uses COFF/PE and macOS Mach-O; the ideas are the same.
  • relocatable means "not yet placed at an address": the linker will decide where its code ends up.
  • size shows the main sections: text (machine code), data (initialised globals) and bss (zero-initialised globals, which take no space in the file). The string "Hello, %s!\n" lives in a read-only data section, which size counts under text, together with small metadata sections such as the unwind tables (.eh_frame).

main.c compiled without ever seeing greet's body. The declaration void greet(const char *who); is a promise that some other object will provide it. Each source file is a separate translation unit: that independence is what makes incremental and parallel builds possible.

Holes for the linker: relocations

If main.o doesn't know where greet will be, what does its call instruction contain? objdump -d -r disassembles the code and shows relocations, the notes that tell the linker which bytes to patch:

bash · try it yourself
mkdir -p obj && cd obj
cat > main.c <<'SRC'
void greet(const char *who);
int main(void) {
    greet("builder");
    return 0;
}
SRC
gcc -c -O1 main.c
objdump -d -r --no-show-raw-insn -M intel main.o | sed -n '/<main>:/,$p'
0000000000000000 <main>:
   0:	endbr64
   4:	sub    rsp,0x8
   8:	lea    rdi,[rip+0x0]        # f <main+0xf>
			b: R_X86_64_PC32	.LC0-0x4
   f:	call   14 <main+0x14>
			10: R_X86_64_PLT32	greet-0x4
  14:	mov    eax,0x0
  19:	add    rsp,0x8
  1d:	ret
  • lea rdi,[rip+0x0] loads the address of the string "builder", but the offset is 0 for now. The relocation R_X86_64_PC32 .LC0-0x4 at offset b says "fill in the distance to the string here" (.LC0 is the compiler's label for the string constant).
  • call 14 <main+0x14> looks like a call to the next instruction. That is a placeholder too: R_X86_64_PLT32 greet-0x4 tells the linker to patch in the distance to greet (through the PLT if greet turns out to live in a shared library).
  • The addresses start at 0 because the object hasn't been placed anywhere yet.

The ELF header

Every ELF file starts with a header saying what it is and what CPU it is for. readelf -h prints it:

bash · try it yourself
mkdir -p obj && cd obj
printf 'int answer(void) { return 42; }\n' > answer.c
gcc -c answer.c
readelf -h answer.o | grep -E 'Class|Data|Type|Machine'
  Class:                             ELF64
  Data:                              2's complement, little endian
  Type:                              REL (Relocatable file)
  Machine:                           Advanced Micro Devices X86-64

Type: REL is a relocatable object. An executable built as a position-independent executable (the default on Ubuntu) shows DYN, as does a shared library. A linker refuses to mix objects with different Machine or Class values: you can't link an ARM object into an x86-64 program. That is the first thing you meet in Cross-Compilation.

Model: patching relocations

A relocation is just "at offset X in this section, write the address of symbol S (plus an addend), relative or absolute". This model links two tiny "objects" by laying them out and patching the holes, using PC-relative arithmetic like R_X86_64_PC32:

js · try it yourself
const objects = [
  { name: "main.o", size: 16, symbols: { main: 0 },
    relocs: [{ at: 10, symbol: "greet", addend: -4 }] },
  { name: "greet.o", size: 24, symbols: { greet: 0 }, relocs: [] },
];

// 1. Layout: place each object one after another, starting at 0x1000.
let addr = 0x1000;
const symtab = {};
for (const o of objects) {
  o.base = addr;
  for (const [sym, off] of Object.entries(o.symbols)) symtab[sym] = addr + off;
  addr += o.size;
}
// 2. Patch: value = S + A - P  (symbol + addend - place)
for (const o of objects) {
  for (const r of o.relocs) {
    const place = o.base + r.at;
    const value = symtab[r.symbol] + r.addend - place;
    console.log(`${o.name}+${r.at} (0x${place.toString(16)}): ${r.symbol} at 0x${symtab[r.symbol].toString(16)} -> write ${value}`);
  }
}
console.log(Object.entries(symtab).map(([s, a]) => `${s}=0x${a.toString(16)}`).join(" "));
main.o+10 (0x100a): greet at 0x1010 -> write 2
main=0x1000 greet=0x1010

The -4 addend exists because x86 measures a relative jump from the end of the 4-byte field, not its start. Real linkers have dozens of relocation types, but every one is a formula like S + A - P.

Test yourself

Why can main.c be compiled to main.o without the source of greet?

  1. The compiler downloads it
  2. A declaration is enough; the call is left as a relocation for the linker to fill
  3. greet is a built-in
  4. Objects contain all source files

What does readelf -h report as the Type of a file made with gcc -c?

  1. EXEC
  2. DYN
  3. REL (relocatable)
  4. CORE

In the model, what formula computes a PC-relative relocation value?

  1. S + A
  2. S + A - P
  3. P - S
  4. S * A