0

I am building a library which roughly boils down to this:

// foo.c
extern void func();

int main() {
 // ...
}

I compile with gcc -o foo func.o foo.c. This results in a binary where the symbol func is before main (i.e. has lower address). However if I add optimization, f.e. -O3 the linker decides to place func after main.

Is there a way to enforce this order?

milck
  • 592
  • 3
  • 12
  • 1
    Why do you need a specific order? – the busybee Jul 28 '22 at 12:25
  • There is a another [discussion here](https://stackoverflow.com/questions/45135/why-does-the-order-in-which-libraries-are-linked-sometimes-cause-errors-in-gcc) that may address what you are looking for. – ryyker Jul 28 '22 at 12:42

1 Answers1

0

Some linkers seems to store their symbols by a key-value table with the hashed symbol as key. And when it comes to allocation, they might use the sequence in the hashed table, which might not be the sequence in which the symbols were encountered.

I never found a way to control this behavior. It happened to me with global variables.

You might get some control if you use a specific linker script and assign segments/sections to the functions.

the busybee
  • 10,755
  • 3
  • 13
  • 30