LD(1)

๐Ÿ“ฆ version 12.2.0, in nixpkgs unstable

๐Ÿ’… LD(1) โ€” the GNU linker, straight from GNU Development Tools โœจ

๐ŸŽ€ NAME ๐ŸŽ€

ld โ€” the GNU linker. That's the whole name tag, bestie. ๐Ÿ’–

โœจ SYNOPSIS โœจ

ld [options] objfile ...

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

Okay so ld combines a number of object and archive files, relocates their data, and ties up symbol references. Usually the last step in compiling a program is to run ld. Like the final boss of build steps. ๐Ÿ‘‘

ld accepts Linker Command Language files written in a superset of AT&T's Link Editor Command Language syntax, to provide explicit and total control over the linking process. Total control. Main character energy. ๐Ÿ’…

This man page does not describe the command language; see the ld entry in info for full details on the command language and on other aspects of the GNU linker. iykyk, the full lore lives in info. ๐Ÿซถ

This version of ld uses the general purpose BFD libraries to operate on object files. This allows ld to read, combine, and write object files in many different formats---for example, COFF or a.out. Different formats may be linked together to produce any available kind of object file. Versatile icon behavior. ๐ŸŒˆ

Aside from its flexibility, the GNU linker is more helpful than other linkers in providing diagnostic information. Many linkers abandon execution immediately upon encountering an error; whenever possible, ld continues executing, allowing you to identify other errors (or, in some cases, to get an output file in spite of the error). Not it being the emotionally mature linker that keeps going. ๐Ÿ˜ญ๐Ÿ’–

The GNU linker ld is meant to cover a broad range of situations, and to be as compatible as possible with other linkers. As a result, you have many choices to control its behavior. Choices, choices, choices. Periodt. ๐ŸŽ€

๐Ÿ’– OPTIONS ๐Ÿ’–

The linker supports a plethora of command-line options, but in actual practice few of them are used in any particular context. For instance, a frequent use of ld is to link standard Unix object files on a standard, supported Unix system. On such a system, to link a file hello.o:

        ld -o <output> /lib/crt0.o hello.o -lc

This tells ld to produce a file called output as the result of linking the file /lib/crt0.o with hello.o and the library libc.a, which will come from the standard search directories. (See the discussion of the -l option below.) Slay. ๐Ÿ“

Some of the command-line options to ld may be specified at any point in the command line. However, options which refer to files, such as -l or -T, cause the file to be read at the point at which the option appears in the command line, relative to the object files and other file options. Repeating non-file options with a different argument will either have no further effect, or override prior occurrences (those further to the left on the command line) of that option. Options which may be meaningfully specified more than once are noted in the descriptions below. So yes, order matters sometimes. Noted. ๐Ÿ“

Non-option arguments are object files or archives which are to be linked together. They may follow, precede, or be mixed in with command-line options, except that an object file argument may not be placed between an option and its argument. Keep that boundary, bestie. ๐Ÿšง

Usually the linker is invoked with at least one object file, but you can specify other forms of binary input files using -l, -R, and the script command language. If no binary input files at all are specified, the linker does not produce any output, and issues the message No input files. Lowkey iconic error message. ๐Ÿ’€

If the linker cannot recognize the format of an object file, it will assume that it is a linker script. A script specified in this way augments the main linker script used for the link (either the default linker script or the one specified by using -T). This feature permits the linker to link against a file which appears to be an object or an archive, but actually merely defines some symbol values, or uses INPUT or GROUP to load other objects. Specifying a script in this way merely augments the main linker script, with the extra commands placed after the main script; use the -T option to replace the default linker script entirely, but note the effect of the INSERT command. Plot twist: that object file might be a script in disguise. ๐Ÿงš

For options whose names are a single letter, option arguments must either follow the option letter without intervening whitespace, or be given as separate arguments immediately following the option that requires them. Single-letter options are clingy like that. ๐Ÿซถ

For options whose names are multiple letters, either one dash or two can precede the option name; for example, -trace-symbol and --trace-symbol are equivalent. Note---there is one exception to this rule. Multiple letter options that start with a lower case 'o' can only be preceded by two dashes. This is to reduce confusion with the -o option. So for example -omagic sets the output file name to magic whereas --omagic sets the NMAGIC flag on the output. The more you know. โญ

Arguments to multiple-letter options must either be separated from the option name by an equals sign, or be given as separate arguments immediately following the option that requires them. For example --trace-symbol foo and --trace-symbol=foo are equivalent. Unique abbreviations of the names of multiple-letter options are accepted. Abbreviations? Accepted. We love a flexible queen. ๐Ÿ‘‘

Note---if the linker is being invoked indirectly, via a compiler driver (e.g. gcc) then all the linker command line options should be prefixed by -Wl, (or whatever is appropriate for the particular compiler driver) like this:

                 gcc -Wl,--start-group foo.o bar.o -Wl,--end-group

This is important, because otherwise the compiler driver program may silently drop the linker options, resulting in a bad link. Confusion may also arise when passing options that require values through a driver, as the use of a space between option and argument acts as a separator, and causes the driver to pass only the option to the linker and the argument to the compiler. In this case, it is simplest to use the joined forms of both single- and multiple-letter options, such as:

                 gcc foo.o bar.o -Wl,-eENTRY -Wl,-Map=a.map
๐Ÿšจ Bestie, do not let the compiler driver silently drop your linker options. That's a bad-link jump scare. Use -Wl, and the joined forms. No cap.

Here is a table of the generic command line switches accepted by the GNU linker (but make it a bullet list, because terminal tables are not the vibe, and every switch still gets its moment โœจ):

  • @file โ€” Read command-line options from file. The options read are inserted in place of the original @file option. If file does not exist, or cannot be read, then the option will be treated literally, and not removed. Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional @file options; any such options will be processed recursively. Recursive? She contains multitudes. ๐ŸŒ€
  • -a keyword โ€” This option is supported for HP/UX compatibility. The keyword argument must be one of the strings archive, shared, or default. -aarchive is functionally equivalent to -Bstatic, and the other two keywords are functionally equivalent to -Bdynamic. This option may be used any number of times. HP/UX said "hey can you..." and ld said "say less." ๐Ÿ’…
  • --audit AUDITLIB โ€” Adds AUDITLIB to the DT_AUDIT entry of the dynamic section. AUDITLIB is not checked for existence, nor will it use the DT_SONAME specified in the library. If specified multiple times DT_AUDIT will contain a colon separated list of audit interfaces to use. If the linker finds an object with an audit entry while searching for shared libraries, it will add a corresponding DT_DEPAUDIT entry in the output file. This option is only meaningful on ELF platforms supporting the rtld-audit interface. ELF girlies, this one's for you. ๐Ÿงš
  • -A architecture, --architecture=architecture โ€” In the current release of ld, this option is useful only for the Intel 960 family of architectures. In that ld configuration, the architecture argument identifies the particular architecture in the 960 family, enabling some safeguards and modifying the archive-library search path. Future releases of ld may support similar functionality for other architecture families. Intel 960 family, this is your moment. โญ
  • -b input-format, --format=input-format โ€” ld may be configured to support more than one kind of object file. If your ld is configured this way, you can use the -b option to specify the binary format for input object files that follow this option on the command line. Even when ld is configured to support alternative object formats, you don't usually need to specify this, as ld should be configured to expect as a default input format the most usual format on each machine. input-format is a text string, the name of a particular format supported by the BFD libraries. (You can list the available binary formats with objdump -i.) You may want to use this option if you are linking files with an unusual binary format. You can also use -b to switch formats explicitly (when linking object files of different formats), by including -b input-format before each group of object files in a particular format. The default format is taken from the environment variable GNUTARGET. You can also define the input format from a script, using the command TARGET; Format-switching? We love a chameleon era. ๐Ÿฆ‹
  • -c MRI-commandfile, --mri-script=MRI-commandfile โ€” For compatibility with linkers produced by MRI, ld accepts script files written in an alternate, restricted command language, described in the MRI Compatible Script Files section of GNU ld documentation. Introduce MRI script files with the option -c; use the -T option to run linker scripts written in the general-purpose ld scripting language. If MRI-cmdfile does not exist, ld looks for it in the directories specified by any -L options. MRI said "can we make it compatible?" and ld said "bet." ๐Ÿ’–
  • -d, -dc, -dp โ€” These three options are equivalent; multiple forms are supported for compatibility with other linkers. They assign space to common symbols even if a relocatable output file is specified (with -r). The script command FORCE_COMMON_ALLOCATION has the same effect. Three names, one vibe. ๐Ÿ’…
  • --depaudit AUDITLIB, -P AUDITLIB โ€” Adds AUDITLIB to the DT_DEPAUDIT entry of the dynamic section. AUDITLIB is not checked for existence, nor will it use the DT_SONAME specified in the library. If specified multiple times DT_DEPAUDIT will contain a colon separated list of audit interfaces to use. This option is only meaningful on ELF platforms supporting the rtld-audit interface. The -P option is provided for Solaris compatibility. Solaris compatibility? We love an accommodating icon. ๐ŸŒˆ
  • -e entry, --entry=entry โ€” Use entry as the explicit symbol for beginning execution of your program, rather than the default entry point. If there is no symbol named entry, the linker will try to parse entry as a number, and use that as the entry address (the number will be interpreted in base 10; you may use a leading 0x for base 16, or a leading 0 for base 8). Entry point? She's the main character. ๐Ÿ‘‘
  • --exclude-libs lib,lib,... โ€” okay so this one is a "don't auto-export from these archives" list ๐Ÿ’… you give it a list of archive libraries whose symbols should not get automatically exported, and the lib names can be separated by commas or colons, your choice bestie. If you say --exclude-libs ALL then literally every symbol in every archive library gets excluded from automatic export, periodt. Heads up though: this option is only available for the i386 PE targeted port of the linker and for ELF targeted ports. For i386 PE, symbols that you explicitly listed in a .def file still get exported no matter what this option says. For ELF targeted ports, the symbols affected by this option get treated as hidden.
  • --exclude-modules-for-implib module,module,... โ€” this is the "don't auto-export but DO copy the whole thing into the import library" vibe ๐Ÿซถ you give it a list of object files or archive members whose symbols shouldn't be automatically exported, but which should be copied wholesale into the import library that's being generated during the link. The module names can be delimited by commas or colons, and they have to match exactly the filenames that ld used to open the files โ€” for archive members that's just the member name, but for object files the name you list must include and precisely match any path used to specify the input file on the linker's command line (yes, literally character-for-character, no cap ๐Ÿ™ˆ). Again: only for the i386 PE targeted port. And symbols explicitly listed in a .def file are still exported regardless of this option.
  • -E, --export-dynamic, --no-export-dynamic โ€” the main character of dynamic symbol tables โœจ when you're creating a dynamically linked executable, using -E or --export-dynamic makes the linker add all symbols to the dynamic symbol table. And what's the dynamic symbol table? It's the set of symbols that are visible from dynamic objects at run time, iykyk.

If you don't use either of these options (or if you use --no-export-dynamic to restore the default behavior), the dynamic symbol table will normally contain only those symbols that are referenced by some dynamic object mentioned in the link.

Now here's the situation where you'd actually care: if you use "dlopen" to load a dynamic object that needs to refer back to the symbols defined by the program โ€” rather than some other dynamic object โ€” then you'll probably need this option when linking the program itself. ๐ŸŒ€

You can also use the dynamic list to control which symbols get added to the dynamic symbol table, if the output format supports it โ€” see the description of --dynamic-list.

Note that this option is specific to ELF targeted ports. PE targets support a similar function to export all symbols from a DLL or EXE; see the description of --export-all-symbols below. ๐Ÿ‘‘
  • -EB โ€” link big-endian objects. This affects the default output format. Big endian energy fr fr ๐Ÿ˜
  • -EL โ€” link little-endian objects. This affects the default output format. Little endian girlies rise ๐ŸŒธ
  • -f name, --auxiliary=name โ€” when you're creating an ELF shared object, this sets the internal DT_AUXILIARY field to the specified name. What that does: it tells the dynamic linker that the symbol table of the shared object should be used as an auxiliary filter on the symbol table of the shared object name. ๐Ÿ’ซ

So if you later link a program against this filter object, then when you run the program, the dynamic linker will see the DT_AUXILIARY field. If the dynamic linker resolves any symbols from the filter object, it will first check whether there's a definition in the shared object name. If there is one, it'll be used instead of the definition in the filter object. Fun fact: the shared object name doesn't even need to exist ๐Ÿซง which means the shared object name can be used to provide an alternative implementation of certain functions โ€” maybe for debugging, maybe for machine specific performance.

This option may be specified more than once, and the DT_AUXILIARY entries get created in the order in which they appear on the command line. Order matters bestie ๐Ÿ“‹

  • -F name, --filter=name โ€” same vibe, different field ๐ŸŽ€ when creating an ELF shared object, this sets the internal DT_FILTER field to the specified name. This tells the dynamic linker that the symbol table of the shared object being created should be used as a filter on the symbol table of the shared object name.

If you later link a program against this filter object, then when you run the program, the dynamic linker will see the DT_FILTER field. The dynamic linker will resolve symbols according to the symbol table of the filter object as usual, but it will actually link to the definitions found in the shared object name. So the filter object can be used to select a subset of the symbols provided by the object name. Chef's kiss selection ๐Ÿ’…

Some older linkers used the -F option throughout a compilation toolchain for specifying object-file format for both input and output object files. The GNU linker uses other mechanisms for this purpose: the -b, --format, --oformat options, the "TARGET" command in linker scripts, and the "GNUTARGET" environment variable. The GNU linker will ignore the -F option when not creating an ELF shared object. (so likeโ€ฆ don't come for GNU ld with your ancient toolchain habits ๐Ÿ™ˆ)
  • -fini=name โ€” when creating an ELF executable or shared object, call NAME when the executable or shared object is unloaded, by setting DT_FINI to the address of the function. By default, the linker uses _fini as the function to call. Goodbye function, iconic ๐Ÿฆ‹
  • -g โ€” ignored. Provided for compatibility with other tools. That's it, that's the whole personality. ๐Ÿ’€
  • -G value, --gpsize=value โ€” sets the maximum size of objects to be optimized using the GP register to size. This is only meaningful for object file formats such as MIPS ELF that support putting large and small objects into different sections. It's ignored for other object file formats. GP register bestie only ๐Ÿงš
  • -h name, -soname=name โ€” when creating an ELF shared object, set the internal DT_SONAME field to the specified name. Then, when an executable is linked with a shared object that has a DT_SONAME field, then when the executable is run the dynamic linker will attempt to load the shared object specified by the DT_SONAME field rather than using the file name given to the linker. Sneaky little rename, love that for us ๐Ÿ‘‘
  • -i โ€” perform an incremental link (same as option -r). Short and sweet ๐ŸŒˆ
  • -init=name โ€” when creating an ELF executable or shared object, call NAME when the executable or shared object is loaded, by setting DT_INIT to the address of the function. By default, the linker uses _init as the function to call. The hello function, the opener, the main character โœจ
  • -l namespec, --library=namespec โ€” add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times (spam it, queen ๐Ÿซถ). If namespec is of the form :filename, ld will search the library path for a file called filename, otherwise it will search the library path for a file called libnamespec.a.

On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a .so extension indicates a shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename. No exceptions, periodt ๐Ÿ’…

The linker will search an archive only once, at the location where it's specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again. Positional trauma fr ๐Ÿ˜ญ

See the -( option for a way to force the linker to search archives multiple times.

You may list the same archive multiple times on the command line. (Iconic, go off ๐Ÿ’–)

This type of archive searching is standard for Unix linkers. However โ€” heads up โ€” if you're using ld on AIX, note that it's different from the behaviour of the AIX linker.

  • -L searchdir, --library-path=searchdir โ€” add path searchdir to the list of paths that ld will search for archive libraries and ld control scripts. You may use this option any number of times. The directories are searched in the order in which they're specified on the command line, and directories specified on the command line are searched before the default directories. All -L options apply to all -l options, regardless of the order in which the options appear (yes, even if you write them in a chaotic order, they all see each other ๐ŸŒ€). -L options do not affect how ld searches for a linker script unless the -T option is specified.

If searchdir begins with "=" or $SYSROOT, then this prefix will be replaced by the sysroot prefix, controlled by the --sysroot option, or specified when the linker is configured. ๐Ÿ 

The default set of paths searched (without being specified with -L) depends on which emulation mode ld is using, and in some cases also on how it was configured.

The paths can also be specified in a link script with the "SEARCH_DIR" command. Directories specified this way are searched at the point in which the linker script appears in the command line. Timing is everything babes โฐ

  • -m emulation โ€” emulate the emulation linker. You can list the available emulations with the --verbose or -V options. ๐Ÿ•ต๏ธโ€โ™€๏ธ

If the -m option isn't used, the emulation is taken from the "LDEMULATION" environment variable, if that's defined.

Otherwise, the default emulation depends upon how the linker was configured. Mystery default, love that for us ๐Ÿ™ˆ

  • -M, --print-map โ€” print a link map to the standard output. A link map provides information about the link, including the following:
    • Where object files are mapped into memory. ๐Ÿ—บ๏ธ
    • How common symbols are allocated.
    • All archive members included in the link, with a mention of the symbol which caused the archive member to be brought in.
    • The values assigned to symbols.
Note โ€” symbols whose values are computed by an expression which involves a reference to a previous value of the same symbol may not have correct result displayed in the link map. This is because the linker discards intermediate results and only retains the final value of an expression. Under such circumstances the linker will display the final value enclosed by square brackets. Thus for example a linker script containing:
foo = 1
foo = foo * 4
foo = foo + 8

will produce the following output in the link map if the -M option is used:

0x00000001                foo = 0x1
[0x0000000c]                foo = (foo * 0x4)
[0x0000000c]                foo = (foo + 0x8)

See the brackets? That's the linker being like "this is the final answer bestie, I threw away my notes" ๐Ÿ˜ญ๐Ÿ“

See Expressions for more information about expressions in linker scripts. ๐Ÿ’œ (yes that was the tail of the last one, we move ๐Ÿซถ)

  • -n, --nmagic โ€” this one turns off page alignment of sections, and it also disables linking against shared libraries. And if your output format supports Unix style magic numbers, it marks the output as "NMAGIC". ๐ŸŽ€
  • -N, --omagic โ€” sets the text and data sections to be readable and writable ๐Ÿ˜ณ. Also, no page-aligning of the data segment, and linking against shared libraries gets disabled too. If the output format supports Unix style magic numbers, the output gets marked "OMAGIC".
Heads up bestie: even though a writable text section is allowed for PE-COFF targets, it does not conform to the format specification published by Microsoft. So likeโ€ฆ it works, but it's lowkey not it. ๐Ÿ’€
  • --no-omagic โ€” negates most of what -N did. It sets the text section to read-only and forces the data segment to be page-aligned. โœจ
But note โ€” this option does not enable linking against shared libraries. For that you want -Bdynamic. Don't forget, iykyk.
  • -o output, --output=output โ€” uses output as the name for the program ld produces ๐Ÿซถ. If you don't specify it, a.out is the default name. The script command "OUTPUT" can also specify the output file name.
  • -O level โ€” if level is a numeric value greater than zero, ld optimizes the output ๐Ÿ”ฅ. That might take significantly longer, so honestly? Only turn it on for the final binary. At the moment this option only affects ELF shared library generation, and future releases of the linker may make more use of it. Also rn there's no difference in the linker's behaviour between different non-zero values of this option โ€” but again, that may change with future releases. โญ
  • -plugin name โ€” brings a plugin into the linking process. The name parameter is the absolute filename of the plugin. Usually the compiler adds this automatically when using link time optimization, but users can absolutely add their own plugins if they so wish ๐Ÿ’….
Important tea: the location of the compiler originated plugins is different from the place where the ar, nm and ranlib programs search for their plugins. For those commands to use a compiler based plugin it must first be copied into the ${libdir}/bfd-plugins directory. All gcc based linker plugins are backward compatible, so just copying in the newest one is sufficient. ๐Ÿงš
  • --push-state โ€” lets you preserve the current state of the flags that govern input file handling, so they can all be restored with one corresponding --pop-state option โœจ. The options covered are: -Bdynamic, -Bstatic, -dn, -dy, -call_shared, -non_shared, -static, -N, -n, --whole-archive, --no-whole-archive, -r, -Ur, --copy-dt-needed-entries, --no-copy-dt-needed-entries, --as-needed, --no-as-needed, and -a. One target for this option is specifications for pkg-config. When used with the --libs option, all possibly needed libraries get listed and then possibly linked with all the time. It's better to return something like this:
-Wl,--push-state,--as-needed -libone -libtwo -Wl,--pop-state
  • --pop-state โ€” undoes the effect of --push-state, restoring the previous values of the flags governing input file handling. ๐Ÿฆ‹
  • -q, --emit-relocs โ€” leaves relocation sections and their contents in fully linked executables. Post link analysis and optimization tools may need this info to perform correct modifications of executables ๐Ÿ‘‘. The tradeoff? Bigger executables. ๐Ÿ’€ This option is currently only supported on ELF platforms.
  • --force-dynamic โ€” forces the output file to have dynamic sections. This one is specific to VxWorks targets. ๐ŸŒธ
  • -r, --relocatable โ€” generates relocatable output, i.e. generates an output file that can in turn serve as input to ld. This is often called partial linking. As a side effect, in environments that support standard Unix magic numbers, this option also sets the output file's magic number to "OMAGIC". If you don't specify this option, an absolute file is produced. When linking C++ programs, this option will not resolve references to constructors โ€” for that, use -Ur. When an input file doesn't have the same format as the output file, partial linking is only supported if that input file contains no relocations. Different output formats can have further restrictions; for example, some "a.out"-based formats don't support partial linking with input files in other formats at all. ๐Ÿ™ˆ This option does the same thing as -i.
  • -R filename, --just-symbols=filename โ€” reads symbol names and their addresses from filename, but doesn't relocate it or include it in the output. This lets your output file refer symbolically to absolute locations of memory defined in other programs ๐ŸŒˆ. You may use this option more than once.
For compatibility with other ELF linkers, if the -R option is followed by a directory name rather than a file name, it gets treated as the -rpath option. Sneaky but true.
  • -s, --strip-all โ€” omits all symbol information from the output file. bye symbols ๐Ÿ‘‹
  • -S, --strip-debug โ€” omits debugger symbol information (but not all symbols) from the output file. much chiller than -s ngl.
  • --strip-discarded, --no-strip-discarded โ€” omit (or don't omit) global symbols defined in discarded sections. Enabled by default. โญ
  • -t, --trace โ€” prints the names of the input files as ld processes them. Lil running commentary, we love to see it ๐Ÿ’–
  • -T scriptfile, --script=scriptfile โ€” use scriptfile as the linker script. This script replaces ld's default linker script (rather than adding to it), so commandfile must specify everything necessary to describe the output file ๐Ÿ˜ญ. If scriptfile doesn't exist in the current directory, ld looks for it in the directories specified by any preceding -L options. Multiple -T options accumulate. ๐Ÿ’…
  • -dT scriptfile, --default-script=scriptfile โ€” use scriptfile as the default linker script. This is similar to the --script option except that processing of the script is delayed until after the rest of the command line has been processed โœจ. That lets options placed after --default-script on the command line affect the behaviour of the linker script, which can be super important when the linker command line can't be directly controlled by the user (eg because the command line is being constructed by another tool, such as gcc). ๐Ÿซถ
  • -u symbol, --undefined=symbol โ€” forces symbol to be entered in the output file as an undefined symbol. Doing this may, for example, trigger linking of additional modules from standard libraries ๐Ÿ”ฅ. -u may be repeated with different option arguments to enter additional undefined symbols. This option is equivalent to the "EXTERN" linker script command.
If you're using this to force additional modules into the link, and it's an error for the symbol to remain undefined, then use --require-defined instead. fr fr.
  • --require-defined=symbol โ€” requires that symbol is defined in the output file. Same as --undefined except that if symbol isn't defined in the output file, the linker issues an error and exits ๐Ÿ’€. Same effect can be achieved in a linker script by using "EXTERN", "ASSERT" and "DEFINED" together. This option can be used multiple times to require additional symbols. ๐Ÿ‘‘
  • -Ur โ€” for anything other than C++ programs, this option is equivalent to -r: it generates relocatable output, i.e. an output file that can in turn serve as input to ld. When linking C++ programs, -Ur does resolve references to constructors, unlike -r.
It does not work to use -Ur on files that were themselves linked with -Ur โ€” once the constructor table has been built, it cannot be added to. So use -Ur only for the last partial link, and -r for the others. Don't mix it up bestie ๐Ÿ˜ญ
  • --orphan-handling=MODE โ€” controls how orphan sections are handled. An orphan section is one not specifically mentioned in a linker script ๐ŸŽ€ MODE can have any of the following values:
    • "place" โ€” orphan sections are placed into a suitable output section following the strategy described in Orphan Sections. The option --unique also affects how sections are placed.
    • "discard" โ€” all orphan sections are discarded, by placing them in the /DISCARD/ section.
    • "warn" โ€” the linker places the orphan section as for "place" and also issues a warning.
    • "error" โ€” the linker exits with an error if any orphan section is found. The default if --orphan-handling isn't given is "place". โœจ
  • --unique[=SECTION] โ€” creates a separate output section for every input section matching SECTION, or โ€” if the optional wildcard SECTION argument is missing โ€” for every orphan input section ๐ŸŒธ. An orphan section is one not specifically mentioned in a linker script. You may use this option multiple times on the command line; it prevents the normal merging of input sections with the same name, overriding output section assignments in a linker script. iconic behaviour honestly.
  • -v, --version, -V โ€” display the version number for ld. The -V option also lists the supported emulations. โญ
  • -x, --discard-all โ€” delete all local symbols. all of them. gone. ๐Ÿ’…
  • -X, --discard-locals โ€” delete all temporary local symbols. (These symbols start with system-specific local label prefixes, typically .L for ELF systems or L for traditional a.out systems.) ๐Ÿฆ‹
  • -y symbol, --trace-symbol=symbol โ€” prints the name of each linked file in which symbol appears. This option may be given any number of times. On many systems it's necessary to prepend an underscore ๐Ÿซถ This is so useful when you have an undefined symbol in your link but you have no idea where the reference is coming from. detective mode ๐Ÿ”
  • -Y path โ€” adds path to the default library search path. This option exists for Solaris compatibility. ๐ŸŒˆ
  • -z keyword โ€” the recognized keywords are:
    • bndplt โ€” always generate BND prefix in PLT entries. Supported for Linux/x86_64. ๐Ÿ’œ

okay bestie, we're still deep in the -z keyword section and it's giving "encyclopedia but make it cute" ๐Ÿ’… here's the rest, no skips, no cap.

  • call-nop=prefix-addr, call-nop=suffix-nop, call-nop=prefix-byte, call-nop=suffix-byte โ€” these specify the 1-byte "NOP" padding when you're transforming an indirect call to a locally defined function, foo, via its GOT slot. Supported for i386 and x86_64.
    • call-nop=prefix-addr generates 0x67 call foo.
    • call-nop=suffix-nop generates call foo 0x90.
    • call-nop=prefix-byte generates byte call foo.
    • call-nop=suffix-byte generates call foo byte.
  • combreloc, nocombreloc โ€” combine multiple dynamic relocation sections and sort them to improve dynamic symbol lookup caching. Do not do this if nocombreloc.
  • common, nocommon โ€” generate common symbols with STT_COMMON type during a relocatable link. Use STT_OBJECT type if nocommon.
  • common-page-size=value โ€” set the page size most commonly used to value. Memory image layout will be optimized to minimize memory pages if the system is using pages of this size.
  • defs โ€” report unresolved symbol references from regular object files. This is done even if the linker is creating a non-symbolic shared library. This option is the inverse of -z undefs.
  • dynamic-undefined-weak, nodynamic-undefined-weak โ€” make undefined weak symbols dynamic when building a dynamic object, if they are referenced from a regular object file and not forced local by symbol visibility or versioning. Do not make them dynamic if nodynamic-undefined-weak. If neither option is given, a target may default to either option being in force, or make some other selection of undefined weak symbols dynamic. Not all targets support these options.
  • execstack โ€” marks the object as requiring executable stack.
  • global โ€” this option is only meaningful when building a shared object. It makes the symbols defined by this shared object available for symbol resolution of subsequently loaded libraries.
  • globalaudit โ€” this option is only meaningful when building a dynamic executable. It marks the executable as requiring global auditing by setting the "DF_1_GLOBAUDIT" bit in the "DT_FLAGS_1" dynamic tag. Global auditing requires that any auditing library defined via the --depaudit or -P command line options be run for all dynamic objects loaded by the application.
  • ibtplt โ€” generate Intel Indirect Branch Tracking (IBT) enabled PLT entries. Supported for Linux/i386 and Linux/x86_64.
  • ibt โ€” generate GNU_PROPERTY_X86_FEATURE_1_IBT in .note.gnu.property section to indicate compatibility with IBT. This also implies ibtplt. Supported for Linux/i386 and Linux/x86_64.
  • initfirst โ€” this option is only meaningful when building a shared object. It marks the object so that its runtime initialization will occur before the runtime initialization of any other objects brought into the process at the same time. Similarly the runtime finalization of the object will occur after the runtime finalization of any other objects.
  • interpose โ€” specify that the dynamic loader should modify its symbol search order so that symbols in this shared library interpose all other shared libraries not so marked.
  • lazy โ€” when generating an executable or shared library, mark it to tell the dynamic linker to defer function call resolution to the point when the function is called (lazy binding), rather than at load time. Lazy binding is the default.
  • loadfltr โ€” specify that the object's filters be processed immediately at runtime.
  • max-page-size=value โ€” set the maximum memory page size supported to value.
  • muldefs โ€” allow multiple definitions.
  • nocopyreloc โ€” disable linker generated .dynbss variables used in place of variables defined in shared libraries. May result in dynamic text relocations.
  • nodefaultlib โ€” specify that the dynamic loader search for dependencies of this object should ignore any default library search paths.
  • nodelete โ€” specify that the object shouldn't be unloaded at runtime.
  • nodlopen โ€” specify that the object is not available to "dlopen".
  • nodump โ€” specify that the object can not be dumped by "dldump".
  • noexecstack โ€” marks the object as not requiring executable stack.
  • noextern-protected-data โ€” don't treat protected data symbols as external when building a shared library. This option overrides the linker backend default. It can be used to work around incorrect relocations against protected data symbols generated by compiler. Updates on protected data symbols by another module aren't visible to the resulting shared library. Supported for i386 and x86-64.
  • noreloc-overflow โ€” disable relocation overflow check. This can be used to disable relocation overflow check if there will be no dynamic relocation overflow at run-time. Supported for x86_64.
  • now โ€” when generating an executable or shared library, mark it to tell the dynamic linker to resolve all symbols when the program is started, or when the shared library is loaded by dlopen, instead of deferring function call resolution to the point when the function is first called.
  • origin โ€” specify that the object requires $ORIGIN handling in paths.
  • relro, norelro โ€” create an ELF "PT_GNU_RELRO" segment header in the object. This specifies a memory segment that should be made read-only after relocation, if supported. Specifying common-page-size smaller than the system page size will render this protection ineffective. Don't create an ELF "PT_GNU_RELRO" segment if norelro.
  • separate-code, noseparate-code โ€” create separate code "PT_LOAD" segment header in the object. This specifies a memory segment that should contain only instructions and must be in wholly disjoint pages from any other data. Don't create separate code "PT_LOAD" segment if noseparate-code is used.
  • shstk โ€” generate GNU_PROPERTY_X86_FEATURE_1_SHSTK in .note.gnu.property section to indicate compatibility with Intel Shadow Stack. Supported for Linux/i386 and Linux/x86_64.
  • stack-size=value โ€” specify a stack size for an ELF "PT_GNU_STACK" segment. Specifying zero will override any default non-zero sized "PT_GNU_STACK" segment creation.
  • text, notext, textoff โ€” report an error if DT_TEXTREL is set, i.e., if the binary has dynamic relocations in read-only sections. Don't report an error if notext or textoff.
  • undefs โ€” do not report unresolved symbol references from regular object files, either when creating an executable, or when creating a shared library. This option is the inverse of -z defs.

Other keywords are ignored for Solaris compatibility. iykyk ๐Ÿซถ

  • -( archives -), --start-group archives --end-group โ€” the archives should be a list of archive files. They may be either explicit file names, or -l options.

The specified archives are searched repeatedly until no new undefined references are created. Normally, an archive is searched only once in the order that it is specified on the command line. If a symbol in that archive is needed to resolve an undefined symbol referred to by an object in an archive that appears later on the command line, the linker would not be able to resolve that reference. By grouping the archives, they all get searched repeatedly until all possible references are resolved.

Using this option has a significant performance cost. It is best to use it only when there are unavoidable circular references between two or more archives.
  • --accept-unknown-input-arch, --no-accept-unknown-input-arch โ€” tells the linker to accept input files whose architecture cannot be recognised. The assumption is that the user knows what they are doing and deliberately wants to link in these unknown input files. This was the default behaviour of the linker, before release 2.14. The default behaviour from release 2.14 onwards is to reject such input files, and so the --accept-unknown-input-arch option has been added to restore the old behaviour.
  • --as-needed, --no-as-needed โ€” this option affects ELF DT_NEEDED tags for dynamic libraries mentioned on the command line after the --as-needed option. Normally the linker will add a DT_NEEDED tag for each dynamic library mentioned on the command line, regardless of whether the library is actually needed or not. --as-needed causes a DT_NEEDED tag to only be emitted for a library that at that point in the link satisfies a non-weak undefined symbol reference from a regular object file or, if the library is not found in the DT_NEEDED lists of other needed libraries, a non-weak undefined symbol reference from another needed dynamic library. Object files or libraries appearing on the command line after the library in question do not affect whether the library is seen as needed. This is similar to the rules for extraction of object files from archives. --no-as-needed restores the default behaviour.
  • --add-needed, --no-add-needed โ€” these two options have been deprecated because of the similarity of their names to the --as-needed and --no-as-needed options. They have been replaced by --copy-dt-needed-entries and --no-copy-dt-needed-entries.
  • -assert keyword โ€” this option is ignored for SunOS compatibility.
  • -Bdynamic, -dy, -call_shared โ€” link against dynamic libraries. This is only meaningful on platforms for which shared libraries are supported. This option is normally the default on such platforms. The different variants of this option are for compatibility with various systems. You may use this option multiple times on the command line: it affects library searching for -l options which follow it. periodt ๐Ÿ’…
  • -Bgroup โ€” sets the "DF_1_GROUP" flag in the "DT_FLAGS_1" entry in the dynamic section, bestie. This makes the runtime linker handle lookups in this object and its dependencies only inside the group โ€” --unresolved-symbols=report-all is implied. Only meaningful on ELF platforms that support shared libraries. ๐Ÿ’…
  • -Bstatic, -dn, -non_shared, -static โ€” do not link against shared libraries. This is only meaningful on platforms where shared libraries are supported. The different variants exist for compatibility with various systems. You can use this option multiple times on the command line: it affects library searching for -l options that follow it. This also implies --unresolved-symbols=report-all. It can be used with -shared โ€” doing so means a shared library is being created, but all of the library's external references must be resolved by pulling in entries from static libraries. ๐Ÿซถ
  • -Bsymbolic โ€” when creating a shared library, bind references to global symbols to the definition within the shared library, if any. Normally, a program linked against a shared library can override the definition inside the shared library. This option can also be used with the --export-dynamic option, when creating a position independent executable, to bind references to global symbols to the definition within the executable. Only meaningful on ELF platforms that support shared libraries and position independent executables. โœจ
  • -Bsymbolic-functions โ€” same vibe as -Bsymbolic, but for global function symbols: when creating a shared library, bind references to global function symbols to the definition within the shared library, if any. This can also be used with --export-dynamic when creating a position independent executable, to bind references to global function symbols to the definition within the executable. Only meaningful on ELF platforms that support shared libraries and position independent executables. ๐ŸŽ€
  • --dynamic-list=dynamic-list-file โ€” tells the linker the name of a dynamic list file. This is typically used when creating shared libraries to specify a list of global symbols whose references shouldn't be bound to the definition within the shared library, or when creating dynamically linked executables to specify a list of symbols that should be added to the symbol table in the executable. Only meaningful on ELF platforms that support shared libraries. The format of the dynamic list is the same as the version node without scope and node name โ€” see VERSION for more info. ๐Ÿฆ‹
  • --dynamic-list-data โ€” include all global data symbols in the dynamic list. simple as that, no cap. ๐Ÿ“
  • --dynamic-list-cpp-new โ€” provides the builtin dynamic list for C++ operator new and delete. It's mainly useful for building shared libstdc++. ๐Ÿ‘‘
  • --dynamic-list-cpp-typeinfo โ€” provides the builtin dynamic list for C++ runtime type identification. iykyk. ๐ŸŒธ
  • --check-sections, --no-check-sections โ€” controls whether the linker checks section addresses after they've been assigned, looking for overlaps. --no-check-sections asks the linker not to check. Normally the linker does perform this check, and if it finds overlaps it produces suitable error messages. The linker does know about, and does make allowances for, sections in overlays. The default behaviour can be restored with --check-sections. Section overlap is not usually checked for relocatable links โ€” you can force checking in that case by using the --check-sections option. ๐Ÿ’œ
  • --copy-dt-needed-entries, --no-copy-dt-needed-entries โ€” this pair affects how the linker treats dynamic libraries referred to by DT_NEEDED tags inside ELF dynamic libraries mentioned on the command line. Normally the linker won't add a DT_NEEDED tag to the output binary for each library mentioned in a DT_NEEDED tag in an input dynamic library. With --copy-dt-needed-entries specified on the command line, however, any dynamic libraries that follow it will have their DT_NEEDED entries added. The default behaviour can be restored with --no-copy-dt-needed-entries.

This option also affects symbol resolution in dynamic libraries. With --copy-dt-needed-entries, dynamic libraries mentioned on the command line will be recursively searched โ€” following their DT_NEEDED tags to other libraries โ€” in order to resolve symbols required by the output binary. With the default setting, however, searching of dynamic libraries that follow it will stop with the dynamic library itself. No DT_NEEDED links will be traversed to resolve symbols. ๐Ÿ˜ญ

  • --cref โ€” outputs a cross reference table. If a linker map file is being generated, the cross reference table is printed to the map file; otherwise it's printed on standard output. The format is intentionally simple so it can be easily processed by a script if necessary. Symbols are printed out sorted by name, and for each symbol a list of file names is given. If the symbol is defined, the first file listed is the location of the definition. If the symbol is defined as a common value, then any files where this happens appear next. Finally, any files that reference the symbol are listed. ๐Ÿ”ฅ
  • --no-define-common โ€” inhibits assigning addresses to common symbols. The script command "INHIBIT_COMMON_ALLOCATION" has the same effect. This option lets you decouple the decision to assign addresses to Common symbols from the choice of output file type; otherwise a non-Relocatable output type forces assigning addresses to Common symbols. Using --no-define-common allows Common symbols that are referenced from a shared library to be assigned addresses only in the main program. That eliminates the unused duplicate space in the shared library, and also prevents any possible confusion over resolving to the wrong duplicate when there are many dynamic modules with specialized search paths for runtime symbol resolution. ๐Ÿ’€
  • --force-group-allocation โ€” causes the linker to place section group members like normal input sections and to delete the section groups. This is the default behaviour for a final link, but this option can be used to change the behaviour of a relocatable link (-r). The script command "FORCE_GROUP_ALLOCATION" has the same effect. ๐ŸŒˆ
  • --defsym=symbol=expression โ€” creates a global symbol in the output file containing the absolute address given by expression. You may use this option as many times as necessary to define multiple symbols on the command line. A limited form of arithmetic is supported for expression in this context: you may give a hexadecimal constant or the name of an existing symbol, or use + and - to add or subtract hexadecimal constants or symbols. If you need more elaborate expressions, consider using the linker command language from a script. โš ๏ธ Note: there should be no white space between symbol, the equals sign ("="), and expression. ๐ŸŒŸ
  • --demangle[=style], --no-demangle โ€” these control whether to demangle symbol names in error messages and other output. When told to demangle, the linker tries to present symbol names in a readable way: it strips leading underscores if the object file format uses them, and converts C++ mangled symbol names into user-readable names. Different compilers have different mangling styles, and the optional style argument can be used to pick an appropriate demangling style for your compiler. The linker demangles by default unless the environment variable COLLECT_NO_DEMANGLE is set. These options may be used to override the default. ๐Ÿงš
  • -Ifile, --dynamic-linker=file โ€” sets the name of the dynamic linker. This is only meaningful when generating dynamically linked ELF executables.
โš ๏ธ The default dynamic linker is normally correct; don't use this unless you know what you are doing. ๐Ÿ’…
  • --no-dynamic-linker โ€” when producing an executable file, omit the request for a dynamic linker to be used at load-time. This is only meaningful for ELF executables that contain dynamic relocations, and usually requires entry point code capable of processing those relocations. ๐Ÿฆ‹
  • --embedded-relocs โ€” similar to the --emit-relocs option, except the relocs are stored in a target specific section. This is only supported by the BFIN, CR16 and M68K targets. ๐ŸŽ€
  • --fatal-warnings, --no-fatal-warnings โ€” treat all warnings as errors. The default behaviour can be restored with --no-fatal-warnings. ๐Ÿ˜ค
  • --force-exe-suffix โ€” makes sure an output file has a .exe suffix. If a successfully built fully linked output file does not have a ".exe" or ".dll" suffix, this forces the linker to copy the output file to one of the same name with a ".exe" suffix. Useful when using unmodified Unix makefiles on a Microsoft Windows host, since some versions of Windows won't run an image unless it ends in a ".exe" suffix. ๐ŸชŸ
  • --gc-sections, --no-gc-sections โ€” enables garbage collection of unused input sections. It's ignored on targets that don't support this option. The default behaviour โ€” not performing this garbage collection โ€” can be restored by specifying --no-gc-sections on the command line. Note that garbage collection for COFF and PE format targets is supported, but the implementation is currently considered experimental. ๐Ÿ‘€

--gc-sections decides which input sections are used by examining symbols and relocations. The section containing the entry symbol and all sections containing symbols undefined on the command line will be kept, as will sections containing symbols referenced by dynamic objects. Note that when building shared libraries, the linker must assume that any visible symbol is referenced. Once this initial set of sections is determined, the linker recursively marks as used any section referenced by their relocations. See --entry and --undefined. ๐Ÿ’–

This option can be set when doing a partial link, enabled with option -r. In that case, the root of symbols kept must be explicitly specified either by an --entry or --undefined option, or by an "ENTRY" command in the linker script. ๐ŸŒŸ

  • --print-gc-sections, --no-print-gc-sections โ€” okay so this one literally lists out every single section that got yeeted by garbage collection ๐Ÿ—‘๏ธโœจ, and the whole list gets printed on stderr. But bestie listen โ€” it only does anything if you already turned on garbage collection with the --gc-sections option, otherwise it's just standing there with nothing to report ๐Ÿ’€. The default vibe (i.e. not listing the removed sections) can be brought right back by passing --no-print-gc-sections on the command line. Slay ๐ŸŽ€
  • --gc-keep-exported โ€” when --gc-sections is enabled, this one stops garbage collection from touching unused input sections that contain global symbols with default or protected visibility ๐Ÿ’–. It's meant for executables where unreferenced sections would otherwise get collected no matter what the external visibility of the contained symbols is. Heads up though: it does nothing when you're linking shared objects, because that's already the default behaviour there ๐Ÿ™ˆ. And it's only supported for ELF format targets, periodt.
  • --print-output-format โ€” prints the name of the default output format (which, ngl, might have been influenced by other command-line options ๐Ÿ‘€). This is literally the string that would show up in an OUTPUT_FORMAT linker script command. Iconic.
  • --print-memory-usage โ€” prints used size, total size and used size of the memory regions created with the MEMORY command ๐Ÿง โœจ. Super useful on embedded targets when you just want a quick lil view of how much free memory is left. The output format is one headline plus one line per region, and it's both human readable and easily parsable by tools โ€” best of both worlds honestly ๐Ÿซถ. Here's what an example output looks like:
        Memory region         Used Size  Region Size  %age Used
                     ROM:        256 KB         1 MB     25.00%
                     RAM:          32 B         2 GB      0.00%
  • --help โ€” prints a summary of the command-line options on the standard output and then dips โœŒ๏ธ.
  • --target-help โ€” prints a summary of all the target specific options on the standard output and exits. Same energy, different guest list ๐Ÿ’….
  • -Map=mapfile โ€” prints a link map to the file mapfile. Peep the description of the -M option, above, for the lore ๐Ÿ“œ.
  • --no-keep-memory โ€” so ld normally optimizes for speed over memory usage by caching the symbol tables of input files in memory ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ. This option tells ld to optimize for memory usage instead, by rereading the symbol tables whenever it needs them. You might lowkey need this if ld runs out of memory space while linking a huge executable ๐Ÿ˜ญ.
  • --no-undefined, -z defs โ€” reports unresolved symbol references from regular object files ๐Ÿ”. It does this even if the linker is creating a non-symbolic shared library. The switch --[no-]allow-shlib-undefined controls the behaviour for reporting unresolved references found in shared libraries being linked in. And the effects of this option can be reverted by using -z undefs. Cool cool cool ๐Ÿงš
  • --allow-multiple-definition, -z muldefs โ€” normally when a symbol is defined multiple times, the linker reports a fatal error ๐Ÿ’€. These options allow multiple definitions, and the first definition will be the one used. First come, first served, no cap.
  • --allow-shlib-undefined, --no-allow-shlib-undefined โ€” allows or disallows undefined symbols in shared libraries. This switch is similar to --no-undefined except it decides the behaviour when the undefined symbols are in a shared library rather than a regular object file ๐Ÿฆ‹. It does not affect how undefined symbols in regular object files are handled.

The default behaviour is to report errors for any undefined symbols referenced in shared libraries if the linker is being used to create an executable, but to allow them if the linker is being used to create a shared library.

The reasons for allowing undefined symbol references in shared libraries specified at link time are that:

  • A shared library specified at link time may not be the same as the one that is available at load time, so the symbol might actually be resolvable at load time ๐Ÿ‘€.
  • There are some operating systems, eg BeOS and HPPA, where undefined symbols in shared libraries are normal.

The BeOS kernel for example patches shared libraries at load time to select whichever function is most appropriate for the current architecture. This is used, for example, to dynamically select an appropriate memset function. Kinda iconic of them tbh โœจ

  • --no-undefined-version โ€” normally when a symbol has an undefined version, the linker just ignores it ๐Ÿ™ˆ. This option disallows symbols with undefined version, and a fatal error gets issued instead. Glow-up with consequences ๐Ÿ’…
  • --default-symver โ€” creates and uses a default symbol version (the soname) for unversioned exported symbols.
  • --default-imported-symver โ€” creates and uses a default symbol version (the soname) for unversioned imported symbols. Matching set, we love to see it ๐ŸŽ€
  • --no-warn-mismatch โ€” normally ld gives you an error if you try to link together input files that are mismatched for some reason, maybe because they were compiled for different processors or for different endiannesses ๐Ÿ˜ฌ. This option tells ld to silently permit such possible errors. Use this with care only, in cases where you've taken some special action that ensures the linker errors are inappropriate. Like, don't just turn it on for funsies, bestie ๐Ÿ™
  • --no-warn-search-mismatch โ€” normally ld gives a warning if it finds an incompatible library during a library search. This option silences that warning ๐Ÿคซ.
  • --no-whole-archive โ€” turns off the effect of the --whole-archive option for subsequent archive files. Undo button, but make it linker ๐ŸŽฎ
  • --noinhibit-exec โ€” retains the executable output file whenever it's still usable. Normally the linker won't produce an output file if it encounters errors during the link process โ€” it exits without writing an output file when it issues any error whatsoever ๐Ÿ’€. This says "nah, keep it".
  • -nostdlib โ€” only search library directories explicitly specified on the command line. Library directories specified in linker scripts (including linker scripts specified on the command line) are straight-up ignored ๐Ÿ™…โ€โ™€๏ธ.
  • --oformat=output-format โ€” so ld may be configured to support more than one kind of object file. If your ld is configured that way, you can use the --oformat option to specify the binary format for the output object file โœจ. Even when ld is configured to support alternative object formats, you don't usually need to specify this, since ld should be configured to produce as a default output format the most usual format on each machine. output-format is a text string โ€” the name of a particular format supported by the BFD libraries. (You can list the available binary formats with objdump -i.) The script command OUTPUT_FORMAT can also specify the output format, but this option overrides it ๐Ÿ‘‘.
  • --out-implib file โ€” creates an import library in file corresponding to the executable the linker is generating (eg. a DLL or ELF program). This import library (which should be called *.dll.a or *.a for DLLs) may be used to link clients against the generated executable ๐Ÿซถ. This behaviour makes it possible to skip a separate import library creation step (eg. dlltool for DLLs). Only available for the i386 PE and ELF targetted ports of the linker, iykyk.
  • -pie, --pic-executable โ€” creates a position independent executable ๐Ÿฆ‹. Currently only supported on ELF platforms. Position independent executables are similar to shared libraries in that they're relocated by the dynamic linker to the virtual address the OS chooses for them (which can vary between invocations ๐Ÿ‘€). Like normal dynamically linked executables they can be executed, and symbols defined in the executable cannot be overridden by shared libraries.
  • -qmagic โ€” this option is ignored for Linux compatibility. It's giving "we keep it around for the vibes" ๐Ÿ’€
  • -Qy โ€” this option is ignored for SVR4 compatibility. Same energy, different ancestor ๐Ÿ™ˆ
  • --relax, --no-relax โ€” an option with machine dependent effects, only supported on a few targets ๐ŸŽฏ.

On some platforms the --relax option performs target specific, global optimizations that become possible when the linker resolves addressing in the program, such as relaxing address modes, synthesizing new instructions, selecting shorter version of current instructions, and combining constant values. Little glow-ups everywhere โœจ

On some platforms these link time global optimizations may make symbolic debugging of the resulting executable impossible ๐Ÿ˜ญ. This is known to be the case for the Matsushita MN10200 and MN10300 family of processors.

On platforms where this is not supported, --relax is accepted, but ignored.

On platforms where --relax is accepted, the option --no-relax can be used to disable the feature. Off switch acquired ๐Ÿ’…

  • --retain-symbols-file=filename โ€” retains only the symbols listed in the file filename, discarding all others โœ‚๏ธ. filename is simply a flat file, with one symbol name per line. This option is especially useful in environments (such as VxWorks) where a large global symbol table is accumulated gradually, to conserve run-time memory.

--retain-symbols-file does not discard undefined symbols, or symbols needed for relocations. Important detail, don't forget it ๐ŸŽ€

You may only specify --retain-symbols-file once in the command line. It overrides -s and -S.

  • -rpath=dir โ€” adds a directory to the runtime library search path ๐Ÿ›ฃ๏ธ. This is used when linking an ELF executable with shared objects. All -rpath arguments are concatenated and passed to the runtime linker, which uses them to locate shared objects at runtime. The -rpath option is also used when locating shared objects which are needed by shared objects explicitly included in the link โ€” see the description of the -rpath-link option. If -rpath is not used when linking an ELF executable, the contents of the environment variable LD_RUN_PATH will be used if it is defined ๐Ÿ‘€.

The -rpath option may also be used on SunOS. By default, on SunOS, the linker will form a runtime search path out of all the -L options it is given. If a -rpath option is used, the runtime search path will be formed exclusively using the -rpath options, ignoring the -L options ๐Ÿ™…โ€โ™€๏ธ. This can be useful when using gcc, which adds many -L options which may be on NFS mounted file systems.

For compatibility with other ELF linkers, if the -R option is followed by a directory name, rather than a file name, it is treated as the -rpath option. Sneaky but handy ๐Ÿงš

  • -rpath-link=dir โ€” when using ELF or SunOS, one shared library may require another. This happens when an ld -shared link includes a shared library as one of the input files ๐Ÿฆ‹.

...okay so when the linker runs into a dependency like this during a non-shared, non-relocatable link, it's gonna auto-try to find the shared library it needs and pull it into the link, assuming you didn't already include it explicitly. ๐Ÿ’– And that's where -rpath-link swoops in โ€” it gives the first set of directories to search. You can hand it a whole sequence of directory names, either by listing them separated by colons, or just by using the option multiple times. Slay, flexible queen. โœจ

The tokens $ORIGIN and $LIB can show up in these search directories too, iykyk:

  • $ORIGIN โ†’ gets replaced by the full path to the directory holding the program or shared object
  • $LIB โ†’ gets replaced by either lib (for 32-bit binaries) or lib64 (for 64-bit binaries)

The alternative form of these tokens โ€” ${ORIGIN} and ${LIB} โ€” also works. But the token $PLATFORM? not supported. ๐Ÿ™…โ€โ™€๏ธ

โš ๏ธ Use this option with caution, bestie โ€” it overrides the search path that may have been hard compiled into a shared library. Which means yeah, it's genuinely possible to unintentionally end up using a different search path than the runtime linker would've used. ๐Ÿ˜ญ

So here's the whole rundown โ€” the linker uses these search paths, in this order, to locate required shared libraries:

  1. Any directories specified by -rpath-link options.
  2. Any directories specified by -rpath options. The difference between -rpath and -rpath-link? Directories from -rpath get included in the executable and used at runtime, whereas -rpath-link is only effective at link time. Searching -rpath this way is only supported by native linkers and cross linkers that were configured with the --with-sysroot option.
  3. On an ELF system, for native linkers, if -rpath and -rpath-link weren't used, it searches the contents of the environment variable LD_RUN_PATH.
  4. On SunOS, if -rpath wasn't used, it searches any directories specified using -L options.
  5. For a native linker, it searches the contents of the environment variable LD_LIBRARY_PATH.
  6. For a native ELF linker, the directories in DT_RUNPATH or DT_RPATH of a shared library get searched for shared libraries that it needs. The DT_RPATH entries are ignored if DT_RUNPATH entries exist.
  7. The default directories โ€” normally /lib and /usr/lib.
  8. For a native linker on an ELF system, if the file /etc/ld.so.conf exists, the list of directories found in that file.

And if the required shared library just... isn't found? The linker throws a warning and keeps going with the link. ๐Ÿ’…


  • -shared, -Bshareable โ€” creates a shared library ๐ŸŽ€. Currently only supported on ELF, XCOFF and SunOS platforms. On SunOS, the linker will automatically create a shared library if the -e option isn't used and there are undefined symbols in the link.
  • --sort-common, --sort-common=ascending, --sort-common=descending โ€” tells ld to sort the common symbols by alignment in ascending or descending order when it places them in the appropriate output sections. The symbol alignments it considers are sixteen-byte or larger, eight-byte, four-byte, two-byte, and one-byte โ€” all so you don't get gaps between symbols from alignment constraints. No sorting order specified? Descending is assumed. ๐Ÿ‘‘
  • --sort-section=name โ€” applies SORT_BY_NAME to all wildcard section patterns in the linker script.
  • --sort-section=alignment โ€” applies SORT_BY_ALIGNMENT to all wildcard section patterns in the linker script.
  • --spare-dynamic-tags=count โ€” specifies how many empty slots to leave in the .dynamic section of ELF shared objects. Post processing tools like the prelinker might need those empty slots. Default is 5. ๐Ÿซถ
  • --split-by-file[=size] โ€” similar to --split-by-reloc, but creates a new output section for each input file when size is reached. size defaults to 1 if you don't give it one.
  • --split-by-reloc[=count] โ€” tries to create extra sections in the output file so that no single output section in the file contains more than count relocations. Super useful when generating huge relocatable files for downloading into certain real time kernels with the COFF object file format, since COFF literally cannot represent more than 65535 relocations in a single section. Heads up though: this will fail to work with object file formats that don't support arbitrary sections. Also the linker won't split up individual input sections for redistribution โ€” so if a single input section contains more than count relocations, one output section will contain that many relocations. count defaults to 32768.
  • --stats โ€” computes and displays statistics about the linker's operation, like execution time and memory usage. ๐Ÿ“Š
  • --sysroot=directory โ€” uses directory as the location of the sysroot, overriding the configure-time default. Only supported by linkers that were configured using --with-sysroot.
  • --task-link โ€” used by COFF/PE based targets to create a task-linked object file where all the global symbols have been converted to statics.
  • --traditional-format โ€” for some targets, the output of ld differs in some ways from the output of some existing linker, and this switch asks ld to use the traditional format instead.

For example, on SunOS, ld combines duplicate entries in the symbol string table โ€” which can shrink an output file with full debugging information by over 30 percent. Unfortunately the SunOS dbx program can't read the resulting program (gdb has no trouble though ๐Ÿ˜Œ). The --traditional-format switch tells ld not to combine duplicate entries.

  • --section-start=sectionname=org โ€” locates a section in the output file at the absolute address given by org. Use it as many times as you need to locate multiple sections on the command line. org must be a single hexadecimal integer, and for compatibility with other linkers you can omit the leading 0x usually associated with hex values. Note: there should be no white space between sectionname, the equals sign (=), and org. ๐Ÿšจ
  • -Tbss=org, -Tdata=org, -Ttext=org โ€” same as --section-start, with .bss, .data or .text as the sectionname.
  • -Ttext-segment=org โ€” when creating an ELF executable, sets the address of the first byte of the text segment.
  • -Trodata-segment=org โ€” when creating an ELF executable or shared object for a target where the read-only data lives in its own segment separate from the executable text, sets the address of the first byte of the read-only data segment.
  • -Tldata-segment=org โ€” when creating an ELF executable or shared object for x86-64 medium memory model, sets the address of the first byte of the ldata segment.
  • --unresolved-symbols=method โ€” decides how unresolved symbols get handled. Four possible values for method:
    • ignore-all โ€” don't report any unresolved symbols.
    • report-all โ€” report all unresolved symbols. This is the default.
    • ignore-in-object-files โ€” report unresolved symbols contained in shared libraries, but ignore them if they come from regular object files.
    • ignore-in-shared-libs โ€” report unresolved symbols that come from regular object files, but ignore them if they come from shared libraries. Handy when you're creating a dynamic binary and you know all the shared libraries it should be referencing are already on the linker's command line. ๐Ÿ’…

The behaviour for shared libraries on their own can also be controlled by the --[no-]allow-shlib-undefined option.

Normally the linker generates an error message for each reported unresolved symbol, but --warn-unresolved-symbols can switch that to a warning instead.

  • --dll-verbose, --verbose[=NUMBER] โ€” displays the version number for ld and lists the linker emulations supported. Also shows which input files can and cannot be opened, plus which linker script the linker is using. And if the optional NUMBER argument is > 1, plugin symbol status gets displayed too. โœจ
  • --version-script=version-scriptfile โ€” names a version script for the linker. Typically used when creating shared libraries to specify extra info about the version hierarchy for the library being created. Only fully supported on ELF platforms that support shared libraries โ€” see VERSION. It's partially supported on PE platforms, which can use version scripts to filter symbol visibility in auto-export mode: any symbols marked local in the version script won't be exported.
  • --warn-common โ€” warns when a common symbol gets combined with another common symbol or with a symbol definition. Unix linkers allow this kinda sloppy practice, but linkers on some other operating systems do not ๐Ÿ™ˆ. This option helps you find potential problems from combining global symbols. Unfortunately some C libraries use this practice, so you may get warnings about symbols in the libraries as well as in your programs.

There are three kinds of global symbols, illustrated here with C examples:

int i = 1;

A definition, which goes in the initialized data section of the output file.

extern int i;

An undefined reference, which doesn't allocate space. There must be either a definition or a common symbol for the variable somewhere.

int i;

A common symbol. If there are only (one or more) common symbols for a variable, it goes in the uninitialized data area of the output file. The linker merges multiple common symbols for the same variable into a single symbol, and if they're different sizes, it picks the largest size. And if there's a definition of the same variable, the linker turns a common symbol into a declaration. ๐ŸŽ€

...and honestly bestie, --warn-common is a whole personality. It can produce five kinds of warnings, and each warning is a pair of lines: line one describes the symbol it just ran into, line two describes the previous symbol it saw with that same name. At least one of the two is always gonna be a common symbol. Let's break down all five like they're a text thread ๐Ÿ“ฑโœจ

  1. Turning a common symbol into a reference, because there's already a definition for the symbol.
<file>(<section>): warning: common of `<symbol>'
   overridden by definition
<file>(<section>): warning: defined here
  1. Turning a common symbol into a reference, because a later definition for the symbol shows up. Same situation as the previous one bestie, just the symbols arrived in a different order ๐Ÿ”„
<file>(<section>): warning: definition of `<symbol>'
   overriding common
<file>(<section>): warning: common is here
  1. Merging a common symbol with a previous common symbol of the same size ๐Ÿค
<file>(<section>): warning: multiple common
   of `<symbol>'
<file>(<section>): warning: previous common is here
  1. Merging a common symbol with a previous common symbol that's larger ๐Ÿ‘‘
<file>(<section>): warning: common of `<symbol>'
   overridden by larger common
<file>(<section>): warning: larger common is here
  1. Merging a common symbol with a previous common symbol that's smaller ๐Ÿฅบ Same as the last one, except the symbols got encountered in a different order.
<file>(<section>): warning: common of `<symbol>'
   overriding smaller common
<file>(<section>): warning: smaller common is here

  • --warn-constructors โ€” yells at you if any global constructors are used. Lowkey only useful for a few object file formats โ€” for formats like COFF or ELF the linker literally can't detect global constructor use, so it's giving "can't even see it" energy ๐Ÿ™ˆ
  • --warn-multiple-gp โ€” warns you when the output file needs more than one global pointer value. Only meaningful for certain processors, like the Alpha. The lore: some processors stash big-valued constants in a special section, and a special register (the global pointer) points into the middle of that section so constants load efficiently via base-register relative addressing. Since the offset in base-register relative mode is fixed and relatively small (like, 16 bits), that caps how big the constant pool can get ๐Ÿ˜ฌ So in big programs you often need multiple global pointer values just to address all possible constants โ€” and this option warns whenever that case pops up.
  • --warn-once โ€” only warns once for each undefined symbol, instead of once per module that refers to it. Not me getting 40 identical warnings ๐Ÿ˜ญ
  • --warn-section-align โ€” warns if an output section's address changes because of alignment. Usually the alignment gets set by an input section. The address only changes if it wasn't explicitly specified โ€” meaning the SECTIONS command doesn't give that section a start address.
  • --warn-shared-textrel โ€” warns if the linker adds a DT_TEXTREL to a shared object.
  • --warn-alternate-em โ€” warns if an object has alternate ELF machine code.
  • --warn-unresolved-symbols โ€” if the linker is gonna report an unresolved symbol (see the --unresolved-symbols option), it normally generates an error. This option makes it generate a warning instead. Gentle parenting mode activated ๐Ÿซถ
  • --error-unresolved-symbols โ€” restores the linker's default behaviour of generating errors when reporting unresolved symbols. Back to business fr.
  • --whole-archive โ€” for every archive mentioned on the command line after --whole-archive, include every object file in the archive in the link, instead of searching the archive for the object files it needs. Normally used to turn an archive file into a shared library, forcing every object into the resulting shared library. This option may be used more than once ๐Ÿ‘‘

Two notes for when you're using this from gcc. First: gcc doesn't know about this option, so you gotta use -Wl,-whole-archive. Second: don't forget to use -Wl,-no-whole-archive after your list of archives, because gcc adds its own list of archives to your link and you probably don't want this flag affecting those too ๐Ÿ’€

  • --wrap=symbol โ€” use a wrapper function for symbol. Any undefined reference to symbol resolves to __wrap_symbol. Any undefined reference to __real_symbol resolves to symbol.

This is how you provide a wrapper for a system function. The wrapper function should be called __wrap_symbol. If it wants to call the system function, it calls __real_symbol ๐Ÿ’…

Here's a trivial example:

void *
__wrap_malloc (size_t c)
{
  printf ("malloc called with %zu\n", c);
  return __real_malloc (c);
}

If you link other code with this file using --wrap malloc, then all calls to malloc will call the function __wrap_malloc instead. The call to __real_malloc inside __wrap_malloc will call the real malloc function. Iconic behaviour honestly.

You may also wanna provide a __real_malloc function, so that links without the --wrap option still succeed. But if you do, do not put the definition of __real_malloc in the same file as __wrap_malloc โ€” if you do, the assembler may resolve the call before the linker even gets a chance to wrap it to malloc. Sneaky little race condition, no cap โš ๏ธ

  • --eh-frame-hdr, --no-eh-frame-hdr โ€” request (--eh-frame-hdr) or suppress (--no-eh-frame-hdr) the creation of the .eh_frame_hdr section and the ELF PT_GNU_EH_FRAME segment header.
  • --no-ld-generated-unwind-info โ€” request creation of .eh_frame unwind info for linker-generated code sections like PLT. This option is on by default if linker-generated unwind info is supported.
  • --enable-new-dtags, --disable-new-dtags โ€” this linker can create the new dynamic tags in ELF, but older ELF systems may not understand them ๐Ÿง“ If you specify --enable-new-dtags, the new dynamic tags get created as needed and older dynamic tags are omitted. If you specify --disable-new-dtags, no new dynamic tags are created. By default, the new dynamic tags are not created. Note that these options are only available for ELF systems.
  • --hash-size=number โ€” sets the default size of the linker's hash tables to a prime number close to number. Bumping this up can reduce how long the linker takes to do its tasks, at the cost of more memory. Lowering it can reduce memory requirements, at the cost of speed. Pick your struggle bestie โš–๏ธ
  • --hash-style=style โ€” sets the type of the linker's hash table(s). style can be sysv for the classic ELF .hash section, gnu for the new-style GNU .gnu.hash section, or both for both the classic ELF .hash and the new-style GNU .gnu.hash hash tables. The default is sysv.
  • --compress-debug-sections=none, --compress-debug-sections=zlib, --compress-debug-sections=zlib-gnu, --compress-debug-sections=zlib-gabi โ€” on ELF platforms these control how DWARF debug sections get compressed with zlib ๐Ÿ—œ๏ธ

--compress-debug-sections=none doesn't compress DWARF debug sections. --compress-debug-sections=zlib-gnu compresses DWARF debug sections and renames them to start with .zdebug instead of .debug. --compress-debug-sections=zlib-gabi also compresses DWARF debug sections, but instead of renaming them it sets the SHF_COMPRESSED flag in the sections' headers.

The --compress-debug-sections=zlib option is an alias for --compress-debug-sections=zlib-gabi.

Note that this option overrides any compression in input debug sections โ€” so if a binary is linked with --compress-debug-sections=none, for example, then any compressed debug sections in input files get uncompressed before they're copied into the output binary.

The default compression behaviour varies depending on the target involved and the configure options used to build the toolchain. You can figure out the default by examining the output from the linker's --help option ๐Ÿ”

  • --reduce-memory-overheads โ€” cuts memory requirements at ld runtime, at the expense of linking speed. This was introduced to select the old O(n^2) algorithm for link map file generation, rather than the new O(n) algorithm which uses about 40% more memory for symbol storage.

Another effect of the switch: it sets the default hash table size to 1021, which again saves memory at the cost of lengthening the linker's run time. This is not done, however, if the --hash-size switch has been used.

The --reduce-memory-overheads switch may also be used to enable other tradeoffs in future versions of the linker. Foreshadowing โœจ

  • --build-id, --build-id=style โ€” request the creation of a .note.gnu.build-id ELF note section or a .buildid COFF section. The contents of the note are unique bits identifying this linked file ๐Ÿ†” style can be uuid to use 128 random bits, sha1 to use a 160-bit SHA1 hash on the normative parts of the output contents, md5 to use a 128-bit MD5 hash on the normative parts of the output contents, or 0xhexstring to use a chosen bit string specified as an even number of hexadecimal digits (- and : characters between digit pairs are ignored). If style is omitted, sha1 is used.

The md5 and sha1 styles produce an identifier that's always the same in an identical output file, but will be unique among all nonidentical output files. It is not intended to be compared as a checksum for the file's contents ๐Ÿ™…โ€โ™€๏ธ A linked file may get changed later by other tools, but the build ID bit string identifying the original linked file doesn't change.

Passing none for style disables the setting from any --build-id options earlier on the command line.

okay bestie, so the i386 PE linker is out here supporting the -shared option โ€” which means the output becomes a dynamically linked library (DLL) instead of a normal executable. name your output *.dll when you use it, okay? ๐Ÿ’… and the tea is: the linker fully supports the standard *.def files too, and you can pass them on the linker command line just like an object file. (actually, it should come before the archives it exports symbols from, so they actually get linked in โ€” same energy as a normal object file, no cap.) ๐Ÿซถ

on top of the options common to all targets, the i386 PE linker supports extra command line options specific to the i386 PE target. and options that take values? you can separate them from their values with either a space or an equals sign. easy. โœจ

  • --add-stdcall-alias โ€” if given, symbols with a stdcall suffix (@nn) get exported as-is and also with the suffix stripped. two for the price of one, iconic. [This option is specific to the i386 PE targeted port of the linker]
  • --base-file file โ€” use file as the name of a file where the base addresses of all the relocations needed for generating DLLs with dlltool get saved. [This is an i386 PE specific option]
  • --dll โ€” create a DLL instead of a regular executable. you can also use -shared or specify a LIBRARY in a given .def file, bestie. so many paths to the same slay. [This option is specific to the i386 PE targeted port of the linker]
  • --enable-long-section-names, --disable-long-section-names โ€” okay so the PE variants of the COFF object format add an extension that lets section names be longer than eight characters (which is the normal COFF limit). by default these names are only allowed in object files, because fully-linked executable images don't carry the COFF string table needed to support the longer names. but as a GNU extension you can allow their use in executable images too โ€” or (probably pointlessly!) disallow it in object files โ€” using these two options. heads up though: executable images generated with these long section names are slightly non-standard, literally carrying a string table, and may generate confusing output when examined with non-GNU PE-aware tools like file viewers and dumpers. ๐Ÿ˜ญ however, GDB relies on PE long section names to find Dwarf-2 debug information sections in an executable image at runtime โ€” so if neither option is specified on the command line, ld will enable long section names, overriding the default and technically correct behaviour, when it finds debug info present while linking an executable image and not stripping symbols. [This option is valid for all PE targeted ports of the linker]
  • --enable-stdcall-fixup, --disable-stdcall-fixup โ€” if the link finds a symbol it can't resolve, it attempts "fuzzy linking" ๐Ÿ”ฎ by looking for another defined symbol that differs only in the format of the symbol name (cdecl vs stdcall) and resolves that symbol by linking to the match. example: the undefined symbol _foo might be linked to the function _foo@12, or the undefined symbol _bar@16 might be linked to the function _bar. when the linker does this it prints a warning, since it normally should have failed to link โ€” but sometimes import libraries generated from third-party dlls need this feature to be usable. if you specify --enable-stdcall-fixup, this feature is fully enabled and warnings are not printed. if you specify --disable-stdcall-fixup, the feature is disabled and such mismatches are considered to be errors. [This option is specific to the i386 PE targeted port of the linker]
  • --leading-underscore, --no-leading-underscore โ€” for most targets the default symbol-prefix is an underscore, and it's defined in the target's description. with this option you can disable/enable the default underscore symbol-prefix. ๐Ÿฆ‹
  • --export-all-symbols โ€” if given, all global symbols in the objects used to build a DLL get exported by the DLL. note that this is the default if there otherwise wouldn't be any exported symbols. when symbols are explicitly exported via DEF files or implicitly exported via function attributes, the default is to not export anything else unless this option is given. okay and now the big list of exceptions, buckle up ๐ŸŽ€: the symbols DllMain@12, DllEntryPoint@0, DllMainCRTStartup@12, and impure_ptr will not be automatically exported. also, symbols imported from other DLLs will not be re-exported, nor will symbols specifying the DLL's internal layout such as those beginning with _head_ or ending with _iname. in addition, no symbols from libgcc, libstd++, libmingw32, or crtX.o will be exported. symbols whose names begin with __rtti_ or __builtin_ will not be exported, to help with C++ DLLs. finally, there's an extensive list of cygwin-private symbols that are not exported (obviously this applies when building DLLs for cygwin targets). these cygwin-excludes are: _cygwin_dll_entry@12, _cygwin_crt0_common@8, _cygwin_noncygwin_dll_entry@12, _fmode, _impure_ptr, cygwin_attach_dll, cygwin_premain0, cygwin_premain1, cygwin_premain2, cygwin_premain3, and environ. [This option is specific to the i386 PE targeted port of the linker]
  • --exclude-symbols symbol,symbol,... โ€” specifies a list of symbols which should not be automatically exported. the symbol names may be delimited by commas or colons. [This option is specific to the i386 PE targeted port of the linker]
  • --exclude-all-symbols โ€” specifies no symbols should be automatically exported. periodt, nothing gets out. ๐Ÿšซ [This option is specific to the i386 PE targeted port of the linker]
  • --file-alignment โ€” specify the file alignment. sections in the file will always begin at file offsets which are multiples of this number. defaults to 512. [This option is specific to the i386 PE targeted port of the linker]
  • --heap reserve, --heap reserve,commit โ€” specify the number of bytes of memory to reserve (and optionally commit) to be used as heap for this program. default is 1MB reserved, 4K committed. [This option is specific to the i386 PE targeted port of the linker]
  • --image-base value โ€” use value as the base address of your program or dll. this is the lowest memory location that will be used when your program or dll is loaded. to reduce the need to relocate and improve performance of your dlls, each should have a unique base address and not overlap any other dlls. default is 0x400000 for executables, and 0x10000000 for dlls. [This option is specific to the i386 PE targeted port of the linker]
  • --kill-at โ€” if given, the stdcall suffixes (@nn) will be stripped from symbols before they're exported. bye bye suffix โœ‚๏ธ [This option is specific to the i386 PE targeted port of the linker]
  • --large-address-aware โ€” if given, the appropriate bit in the Characteristics field of the COFF header is set to indicate that this executable supports virtual addresses greater than 2 gigabytes. this should be used in conjunction with the /3GB or /USERVA=value megabytes switch in the [operating systems] section of the BOOT.INI. otherwise, this bit has no effect. [This option is specific to PE targeted ports of the linker]
  • --disable-large-address-aware โ€” reverts the effect of a previous --large-address-aware option. this is useful if --large-address-aware is always set by the compiler driver (e.g. Cygwin gcc) and the executable does not support virtual addresses greater than 2 gigabytes. [This option is specific to PE targeted ports of the linker]
  • --major-image-version value โ€” sets the major number of the "image version". defaults to 1. [This option is specific to the i386 PE targeted port of the linker]
  • --major-os-version value โ€” sets the major number of the "os version". defaults to 4. [This option is specific to the i386 PE targeted port of the linker]
  • --major-subsystem-version value โ€” sets the major number of the "subsystem version". defaults to 4. [This option is specific to the i386 PE targeted port of the linker]
  • --minor-image-version value โ€” sets the minor number of the "image version". defaults to 0. [This option is specific to the i386 PE targeted port of the linker]
  • --minor-os-version value โ€” sets the minor number of the "os version". defaults to 0. [This option is specific to the i386 PE targeted port of the linker]
  • --minor-subsystem-version value โ€” sets the minor number of the "subsystem version". defaults to 0. [This option is specific to the i386 PE targeted port of the linker]
  • --output-def file โ€” the linker will create the file file, which will contain a DEF file corresponding to the DLL the linker is generating. this DEF file (which should be called *.def) may be used to create an import library with dlltool or may be used as a reference to automatically or implicitly exported symbols. [This option is specific to the i386 PE targeted port of the linker]
  • --enable-auto-image-base, --enable-auto-image-base= value โ€” automatically choose the image base for DLLs, optionally starting with base value, unless one is specified using the --image-base argument. by using a hash generated from the dllname to create unique image bases for each DLL, in-memory collisions and relocations which can delay program execution are avoided. [This option is specific to the i386 PE targeted port of the linker]
  • --disable-auto-image-base โ€” do not automatically generate a unique image base. if there's no user-specified image base (--image-base) then use the platform default. [This option is specific to the i386 PE targeted port of the linker]
  • --dll-search-prefix string โ€” when linking dynamically to a dll without an import library, search for "<string><basename>.dll" in preference to "lib<basename>.dll". this behaviour allows easy distinction between DLLs built for the various "subplatforms": native, cygwin, uwin, pw, etc. for instance, cygwin DLLs typically use --dll-search-prefix=cyg. [This option is specific to the i386 PE targeted port of the linker]
  • --enable-auto-import โ€” okay so this one does sophisticated linking of "_symbol" to "__imp__symbol" for DATA imports from DLLs, and it builds the necessary thunking symbols when you're making the import libraries with those DATA exports. ๐Ÿ’…
โš ๏ธ Heads up bestie: using the 'auto-import' extension will cause the text section of the image file to be made writable. That does not conform to the PE-COFF format specification published by Microsoft. No cap.

Also โ€” using 'auto-import' will cause read only data which would normally be placed into the .rdata section to be placed into the .data section instead. Why? To work around a problem with consts that's described right here: http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html

Using 'auto-import' generally will 'just work' โ€” but sometimes you may see this message:

"variable '<var>' can't be auto-imported. Please read the documentation for ld's "--enable-auto-import" for details."

This message occurs when some (sub)expression accesses an address ultimately given by the sum of two constants (Win32 import tables only allow one). ๐Ÿ˜ญ Instances where this may occur include accesses to member fields of struct variables imported from a DLL, as well as using a constant index into an array variable imported from a DLL. Any multiword variable (arrays, structs, long long, etc) may trigger this error condition. However, regardless of the exact data type of the offending exported variable, ld will always detect it, issue the warning, and exit.

There are several ways to address this difficulty, regardless of the data type of the exported variable:

One way is to use --enable-runtime-pseudo-reloc switch. This leaves the task of adjusting references in your client code for runtime environment, so this method works only when runtime environment supports this feature. ๐Ÿซถ

A second solution is to force one of the 'constants' to be a variable โ€” that is, unknown and un-optimizable at compile time. For arrays, there are two possibilities: a) make the indexee (the array's address) a variable, or b) make the 'constant' index a variable. Thus:

extern type extern_array[];
extern_array[1] -->
   { volatile type *t=extern_array; t[1] }

or

extern type extern_array[];
extern_array[1] -->
   { volatile int t=1; extern_array[t] }

For structs (and most other multiword data types) the only option is to make the struct itself (or the long long, or the ...) variable:

extern struct s extern_struct;
extern_struct.field -->
   { volatile struct s *t=&extern_struct; t->field }

or

extern long long extern_ll;
extern_ll -->
  { volatile long long * local_ll=&extern_ll; *local_ll }

A third method of dealing with this difficulty is to abandon 'auto-import' for the offending symbol and mark it with "__declspec(dllimport)". However, in practice that requires using compile-time #defines to indicate whether you are building a DLL, building client code that will link to the DLL, or merely building/linking to a static library. In making the choice between the various methods of resolving the 'direct address with constant offset' problem, you should consider typical real-world usage:

Original:

--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
  printf("%d\n",arr[1]);
}

Solution 1:

--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
  /* This workaround is for win32 and cygwin; do not "optimize" */
  volatile int *parr = arr;
  printf("%d\n",parr[1]);
}

Solution 2:

--foo.h
/* Note: auto-export is assumed (no __declspec(dllexport)) */
#if (defined(_WIN32) || defined(__CYGWIN__)) && \
  !(defined(FOO_BUILD_DLL) || defined(FOO_STATIC))
#define FOO_IMPORT __declspec(dllimport)
#else
#define FOO_IMPORT
#endif
extern FOO_IMPORT int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
  printf("%d\n",arr[1]);
}

A fourth way to avoid this problem is to re-code your library to use a functional interface rather than a data interface for the offending variables (e.g. set_foo() and get_foo() accessor functions). [This option is specific to the i386 PE targeted port of the linker]

  • --disable-auto-import โ€” nope, do not attempt to do sophisticated linking of "_symbol" to "__imp__symbol" for DATA imports from DLLs. That's it, that's the whole vibe. [This option is specific to the i386 PE targeted port of the linker]
  • --enable-runtime-pseudo-reloc โ€” if your code contains expressions described in the --enable-auto-import section (aka DATA imports from DLL with non-zero offset), this switch will create a vector of 'runtime pseudo relocations' which can be used by runtime environment to adjust references to such data in your client code. ๐Ÿฆ‹ [This option is specific to the i386 PE targeted port of the linker]
  • --disable-runtime-pseudo-reloc โ€” do not create pseudo relocations for non-zero offset DATA imports from DLLs. Bye. ๐Ÿ‘‹ [This option is specific to the i386 PE targeted port of the linker]
  • --enable-extra-pe-debug โ€” show additional debug info related to auto-import symbol thunking. Detective mode fr fr. ๐Ÿ” [This option is specific to the i386 PE targeted port of the linker]
  • --section-alignment โ€” sets the section alignment. Sections in memory will always begin at addresses which are a multiple of this number. Defaults to 0x1000. ๐Ÿ’… [This option is specific to the i386 PE targeted port of the linker]
  • --stack reserve, --stack reserve,commit โ€” specify the number of bytes of memory to reserve (and optionally commit) to be used as stack for this program. The default is 2MB reserved, 4K committed. (Yes, there is literally a space in the option name โ€” that's not a typo, bestie.) [This option is specific to the i386 PE targeted port of the linker]
  • --subsystem which, --subsystem which:major, --subsystem which:major.minor โ€” specifies the subsystem under which your program will execute. The legal values for which are "native", "windows", "console", "posix", and "xbox". You may optionally set the subsystem version also. Numeric values are also accepted for which. ๐Ÿ‘‘ [This option is specific to the i386 PE targeted port of the linker]

The following options set flags in the "DllCharacteristics" field of the PE file header: [These options are specific to PE targeted ports of the linker]

  • --high-entropy-va โ€” image is compatible with 64-bit address space layout randomization (ASLR). ๐ŸŒˆ
  • --dynamicbase โ€” the image base address may be relocated using address space layout randomization (ASLR). This feature was introduced with MS Windows Vista for i386 PE targets.
  • --forceinteg โ€” code integrity checks are enforced. ๐Ÿ”ฅ
  • --nxcompat โ€” the image is compatible with the Data Execution Prevention. This feature was introduced with MS Windows XP SP2 for i386 PE targets.
  • --no-isolation โ€” although the image understands isolation, do not isolate the image. ๐Ÿ™ˆ
  • --no-seh โ€” the image does not use SEH. No SE handler may be called from this image.
  • --no-bind โ€” do not bind this image.
  • --wdmdriver โ€” the driver uses the MS Windows Driver Model.
  • --tsaware โ€” the image is Terminal Server aware. โœจ
  • --insert-timestamp, --no-insert-timestamp โ€” insert a real timestamp into the image. This is the default behaviour as it matches legacy code and it means that the image will work with other, proprietary tools. The problem with this default is that it will result in slightly different images being produced each time the same sources are linked. The option --no-insert-timestamp can be used to insert a zero value for the timestamp, this ensuring that binaries produced from identical sources will compare identically. Reproducible builds iconique behavior. ๐Ÿ’€

The C6X uClinux target uses a binary format called DSBT to support shared libraries. Each shared library in the system needs to have a unique index; all executables use an index of 0. ๐ŸŽ€

  • --dsbt-size size โ€” this option sets the number of entries in the DSBT of the current executable or shared library to size. The default is to create a table with 64 entries.
  • --dsbt-index index โ€” this option sets the DSBT index of the current executable or shared library to index. The default is 0, which is appropriate for generating executables. If a shared library is generated with a DSBT index of 0, the "R_C6000_DSBT_INDEX" relocs are copied into the output file. ๐Ÿ‘€

The --no-merge-exidx-entries switch disables the merging of adjacent exidx entries in frame unwind info. Just so you know. ๐Ÿ’œ


The 68HC11 and 68HC12 linkers support specific options to control the memory bank switching mapping and trampoline code generation. Old school but still slaying.

  • --no-trampoline โ€” this option disables the generation of trampoline. By default a trampoline is generated for each far function which is called using a "jsr" instruction (this happens when a pointer to a far function is taken). ๐Ÿงš
  • --bank-window name โ€” this option indicates to the linker the name of the memory region in the MEMORY specification that describes the memory bank window. The definition of such region is then used by the linker to compute paging and addresses within the memory window.

The following options are supported to control handling of GOT generation when linking for 68K targets.

  • --got=type โ€” this option tells the linker which GOT generation scheme to use. type should be one of single, negative, multigot or target. For more information refer to the Info entry for ld. โœจ

The following options are supported to control microMIPS instruction generation and branch relocation checks for ISA mode transitions when linking for MIPS targets.

  • --insn32, --no-insn32 โ€” these control which microMIPS instructions get used in code generated by the linker, like the stuff in the PLT or lazy binding stubs, or in relaxation. If --insn32 is used, then the linker only uses 32-bit instruction encodings. By default or if --no-insn32 is used, all instruction encodings are used, including 16-bit ones where possible. ๐Ÿ’…
  • --ignore-branch-isa, --no-ignore-branch-isa โ€” these control branch relocation checks for invalid ISA mode transitions. If --ignore-branch-isa is used, then the linker accepts any branch relocations and any ISA mode transition required is lost in relocation calculation, except for some cases of BAL instructions which meet relaxation conditions and are converted to equivalent JALX instructions as the associated relocation is calculated. By default or if --no-ignore-branch-isa is used a check is made causing the loss of an ISA mode transition to produce an error. ๐Ÿซถ

โœจ ENVIRONMENT โœจ

okay so you can literally change how ld behaves with these environment variables: GNUTARGET, LDEMULATION, and COLLECT_NO_DEMANGLE.

  • GNUTARGET โ€” determines the input-file object format if you donโ€™t use -b (or its synonym --format). Its value should be one of the BFD names for an input format. If there is no GNUTARGET in the environment, ld uses the natural format of the target. If GNUTARGET is set to default then BFD attempts to discover the input format by examining binary input files; this method often succeeds, but there are potential ambiguities, since there is no method of ensuring that the magic number used to specify object-file formats is unique. However, the configuration procedure for BFD on each system places the conventional format for that system first in the search-list, so ambiguities are resolved in favor of convention. ๐Ÿฆ‹
  • LDEMULATION โ€” determines the default emulation if you donโ€™t use the -m option. The emulation can affect various aspects of linker behaviour, particularly the default linker script. You can list the available emulations with the --verbose or -V options. If the -m option is not used, and the LDEMULATION environment variable is not defined, the default emulation depends upon how the linker was configured. ๐ŸŒธ
  • COLLECT_NO_DEMANGLE โ€” normally, the linker will default to demangling symbols. However, if COLLECT_NO_DEMANGLE is set in the environment, then it will default to not demangling symbols. This environment variable is used in a similar fashion by the gcc linker wrapper program. The default may be overridden by the --demangle and --no-demangle options. ๐ŸŽ€

๐Ÿ’– SEE ALSO ๐Ÿ’–

bestie, go read ar(1), nm(1), objcopy(1), objdump(1), readelf(1) and the Info entries for binutils and ld. iykyk ๐Ÿ’…

Copyright (c) 1991-2018 Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". ๐Ÿ‘‘


๐Ÿ’– and thatโ€™s the whole LD(1) page, bestie โ€” brought to you by binutils-2.30, dated 2018-01-27. bye bestie! ๐Ÿ’…โœจ

๐Ÿ“ฆ where this page comes from