What is the difference between executable and relocatable in elf format?

elf

Solution

as you know every compiled executable file is a binary file with address relative and absolute, so relocatable format is a format in which function and other symbols still have there names definition in other word functions and variables are not bound to any specific address. Instead, the addresses are still symbols

look :

unix > gcc -c main.c
unix > readelf --symbols main.o
Num:     Value   Size     Type      Bind       Vis     Ndx  Name
  0:  00000000      0   NOTYPE     LOCAL   DEFAULT     UND
  1:  00000000      0   FILE       LOCAL   DEFAULT     ABS  main.c
  2:  00000000      0   OBJECT    GLOBAL   DEFAULT     3    buf
  3:  00000000      0   OBJECT    GLOBAL   DEFAULT     1    main

unix > gcc main.c -o main
unix > readelf --symbols main
Num:     Value   Size     Type      Bind       Vis     Ndx  Name
 53:  08048460      2     FUNC    GLOBAL   DEFAULT     13   __libc_csu_fini
 54:  08048462      0     FUNC    GLOBAL   HIDDEN      13   __i686.get_pc_thunk.bx
 55:  0804a018      4     OBJECT  GLOBAL   DEFAULT     13   bufp0

do you see what i'm talking about

most of the time we use them as static library

look to the example here :

#ifndef MATH_H
#define MATH_H
int add(int a, int b);
#endif

/* math_test.c */
#include <stdio.h>
#include "math.h"

int main(void)
{
  int result = add(1, 2);
  printf("result: %d\n", result);
  return 0;
}

try to compile it

unix > gcc math_test.c -o math_test
/tmp/cclRibQq.o: In function `main':
math_test.c:(.text+0x19): undefined reference to `add'
collect2: ld returned 1 exit status

that due to function `add` has no body in `math_test.c` so we can do the flowing:

int add(int a, int b)
{
  return a + b;
}

then compile it as a relocatable using gcc

unix > gcc -c math.c                      # Create relocatable obj file (math.o)
unix > readelf -h math.o | grep Type      # Read math.o with readelf
Type:            REL (Relocatable file)   # and verify its type

then you can link it with linker like this :

unix > gcc math_test.c math.o -o math_test
unix > ./math_test
result: 3

a great article about the difference between executable file in elf format and relocatable file in elf format you can find here

Problem

What is the difference between executable file in elf format and relocatable file in elf format?

Original source