PeopleMoutainPeopleSea
PeopleMoutainPeopleSea

Reputation: 1522

How to combine two or more relocatable ELF files into one relocatable ELF file using GNU ld?

I have two x86 assembly source files a.asm and b.asm (written in NASM syntax).

a.asm and b.asm combined is an implementation of the function myfun(int a, int b) which returns a+1+b. But I put the codes into separate files.

; a.asm
global myfun

myfun:
   push ebp
   mov  ebp,esp

   mov eax, [ebp+8]
   inc eax

the second file b.asm contains the rest instructions for myfun

   ; b.asm
   add eax, [ebp+12]
   pop ebp
   ret

Then I used nasm -f elf32 to compile a.asm and b.asm, and get a.o and b.o. After that I combined a.o and b.o using the following link script to get c.o

SECTIONS {

    .text : {

      a.o (.text)

      b.o (.text)

     }

}

The function can be called from a C file and returns correct result.

My question is:

  1. file c.o shows that c.o is executable with a program header, although the function myfun in c.o can be used at link time. How to make c.o a pure relocatable file without a program header?

  2. there are junk instructions (nopw) inserted between a.o (.text) and b.o (.text) in c.o to make it 16-byte aligned (b.o (.text) is started at 16-byte boundary in c.o). Can I add some link script command to make a.o (.text) and b.o (.text) compactly combined so the machine codes in c.o (.text) is just like codes compiled from c.asm where c.asm is obtained using command:

    cat a.asm b.asm > c.asm

Upvotes: 2

Views: 3156

Answers (1)

Jester
Jester

Reputation: 58802

While I am not sure what the point is, here are your answers:

  1. If I understand you correctly, you want to do incremental linking. Use -i or -r switch to ld.
  2. You can set the section alignment either in the assembly source by using SECTION .text ALIGN=1 or in the linker script by using SUBALIGN(1)

Upvotes: 3

Related Questions