Search code examples
linuxcommand-line-argumentsld

Does ld keep the order of input objfiles in the command line in output?


Does ld keep the order of input objfiles in the command line in output? For example, assume the command line is:

ld -o output input1.o input2.o input3.o

Will input1 goes first in output, then input2 and finally input3? So, after loading, will the code in input1 occupy the lowest part in address space, then input2 and input3 in the highest? The platform is Linux 20.04 and GNU development toolchain is the most up-to-date (e.g., the version of ld is 2.34). Thank you.


Solution

  • Depends on your linker scripts. Every link is controlled by a linker script. This script is written in the linker command language.

    From GCC documentation:

    The main purpose of the linker script is to describe how the sections in the input files should be mapped into the output file, and to control the memory layout of the output file. Most linker scripts do nothing more than this. However, when necessary, the linker script can also direct the linker to perform many other operations.

    The linker always uses a linker script. If you do not supply one yourself, the linker will use a default script that is compiled into the linker executable. You can use the --verbose command line option to display the default linker script. Certain command line options, such as -r or -N, will affect the default linker script.

    See https://wiki.osdev.org/Linker_Scripts et al.