pts
pts

Reputation: 87381

How to prevent GNU ld from reordering the object files?

I have a function implemented in i386 assembly spreading over multiple .s files. The result of the function depends on the order the machine code is concatenated, for example:

$ gcc -m32 -Wl,-N -W -Wall -Werror -s -O2 -o calladd calladd.c add10.s double.s add1.s ret.s && ./calladd a b; echo $?
27
$ gcc -m32 -Wl,-N -W -Wall -Werror -s -O2 -o calladd calladd.c add10.s add1.s double.s ret.s && ./calladd a b; echo $?
28

I always want to have the code in ret.s last (because it contains the ret instruction), and I want to vary the order of the other .s files.

How can I make sure that GNU ld emits the code .s files in the order I've specified them? It seems to work by default, but I want the solution to be more resilient, i.e. explicitly disable reordering for these .s files even if reordering gets enabled for other files. Which command-line flags are relevant?

Preferably I want to do it without a linker script.

My example files are:

# calladd.c:
extern int add10(int) __attribute__((regparm(1)));
int main(int argc, char **argv) { (void)argv; return add10(argc); }

# add10.s:
.text
.globl add10
add10:
addl $10, %eax

# add1.s:
.text
.globl add1
add1:
addl $1, %eax

# double.s:
.text
.globl double
double:
addl %eax, %eax

# ret.s:
.text
ret

Upvotes: 2

Views: 392

Answers (1)

pts
pts

Reputation: 87381

Based on the comment of @RossRidge: GNU ld doesn't reorder source files by default, just rely on that. To avoid extra bytes inserted because of alignment, don't use .align or anything similar in the .s files, and put them to the same section .text.

Upvotes: 2

Related Questions