LD(1)
π LD(1) β the GNU linker, bestie edition π
GNU Development Tools Β· ld Β· the one and only
β¨ NAME β¨
ld β the GNU linker. That's it, that's the name, no notes. π«Ά
πΈ SYNOPSIS πΈ
ld [options] objfile ...
like. options first, then a pile of object files. you got this. π
π¦ DESCRIPTION π¦
okay so real talk, what does ld actually do? it takes a bunch of object files and archive files, relocates their data, and ties up all the symbol references. it's giving matchmaker for symbols fr fr. usually the very last step in compiling a program is running ld, so it's literally the grand finale of your build. β¨
ld accepts Linker Command Language files, and those are written in a superset of AT&T's Link Editor Command Language syntax. this exists so you can have explicit and total control over the linking process β full main character energy over your link, no cap. π
this man page does not describe the command language, bestie. for full details on the command language and on other aspects of the GNU linker, see theldentry ininfo. π
this version of ld uses the general purpose BFD libraries to operate on object files. what that buys you: ld can read, combine, and write object files in many different formats β for example, COFF or a.out. and different formats can be linked together to produce any available kind of object file. iconic behavior honestly. π
aside from its flexibility, the GNU linker is more helpful than other linkers in providing diagnostic information. many linkers just abandon execution immediately upon encountering an error β dramatic much? β but whenever possible, ld keeps executing, which lets you identify other errors (or, in some cases, get an output file in spite of the error). she persists. π
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 so many choices to control its behavior. options galore. we love choices. π
π OPTIONS π
the linker supports a plethora of command-line options, but in actual practice few of them are used in any particular context. (not every option is the main character of every build, and that's okay.) 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, bestie, it's coming.) π«Ά
some of the command-line options to ld may be specified at any point in the command line. however β and this is the important part β 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. order matters, periodt. 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. π
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. do not do that. π
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. (a whole lot of nothing. she said no. π)
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. β
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. no mystery spaces. β¨
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. one dash vs two dashes and suddenly it's a completely different situation. iykyk. π
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. β¨
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, bestie, because otherwise the compiler driver program may silently drop the linker options, resulting in a bad link. silent dropping is the villain of this story. π
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
here is a table of the generic command-line switches accepted by the GNU linker:
@fileβ read command-line options from file. the options read are inserted in place of the original@fileoption. 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. (files inside files inside files. it's giving inception. π)
-akeyword β this option is supported for HP/UX compatibility. the keyword argument must be one of the stringsarchive,shared, ordefault.-aarchiveis functionally equivalent to-Bstatic, and the other two keywords are functionally equivalent to-Bdynamic. this option may be used any number of times. β¨--auditAUDITLIB β adds AUDITLIB to theDT_AUDITentry of the dynamic section. AUDITLIB is not checked for existence, nor will it use the DT_SONAME specified in the library. if specified multiple timesDT_AUDITwill 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 correspondingDT_DEPAUDITentry in the output file. this option is only meaningful on ELF platforms supporting the rtld-audit interface. πΈ-binput-format--format=input-format βldmay be configured to support more than one kind of object file. if yourldis configured this way, you can use the-boption to specify the binary format for input object files that follow this option on the command line. even whenldis configured to support alternative object formats, you don't usually need to specify this, asldshould 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 withobjdump -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;
-cMRI-commandfile--mri-script=MRI-commandfile β for compatibility with linkers produced by MRI,ldaccepts 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-Toption to run linker scripts written in the general-purposeldscripting language. if MRI-cmdfile does not exist,ldlooks for it in the directories specified by any-Loptions. π₯-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 commandFORCE_COMMON_ALLOCATIONhas the same effect. π«Ά--depauditAUDITLIB-PAUDITLIB β adds AUDITLIB to theDT_DEPAUDITentry of the dynamic section. AUDITLIB is not checked for existence, nor will it use the DT_SONAME specified in the library. if specified multiple timesDT_DEPAUDITwill contain a colon separated list of audit interfaces to use. this option is only meaningful on ELF platforms supporting the rtld-audit interface. the-Poption is provided for Solaris compatibility. β¨--enable-non-contiguous-regionsβ this option avoids generating an error if an input section does not fit a matching output section. the linker tries to allocate the input section to subseque nt matching output sections, and generates an error only if no output section is large enough. this is useful when several non-contiguous memory regions are available and the input section does not require a particular one. the order in which input sections are evaluated does not change, for instance:
MEMORY {
MEM1 (rwx) : ORIGIN : 0x1000, LENGTH = 0x14
MEM2 (rwx) : ORIGIN : 0x1000, LENGTH = 0x40
MEM3 (rwx) : ORIGIN : 0x2000, LENGTH = 0x40
}
SECTIONS {
mem1 : { *(.data.*); } > MEM1
mem2 : { *(.data.*); } > MEM2
mem3 : { *(.data.*); } > MEM2
}
to be continued, bestie β more linker lore incoming π
with input sections:
.data.1: size 8
.data.2: size 0x10
.data.3: size 4
and that whole thing lands with .data.1 affected to mem1, and .data.2 plus .data.3 affected to mem2 β even though .data.3 would have fit in mem3. Yeah bestie, it really said "close enough" π
Heads up: this option is incompatible with INSERT statements because it changes the way input sections are mapped to output sections. So like⦠pick a lane, okay?
--enable-non-contiguous-regions-warningsβ turns on warnings for when--enable-non-contiguous-regionslets through possibly-unexpected matches in section mapping. Why do you care? Because those sneaky matches can end up silently discarding a section instead of straight-up failing because it didn't fit any output region. Silent deletion is NOT the vibe, so flip this on. π¨-e entry,--entry=entryβ use entry as the explicit symbol for where your program starts executing, instead of the default entry point. And if there's no symbol named entry? The linker tries to parse entry as a number and uses that as the entry address. That number is interpreted in base 10, but you can use a leading0xfor base 16, or a leading0for base 8. It's giving "I'll figure it out myself" π--exclude-libs lib,lib,...β gives a list of archive libraries whose symbols should not be automatically exported. Delimit the library names with commas or colons. And--exclude-libs ALLexcludes symbols in all archive libraries from automatic export. β¨
Availability check, because this one's picky: only for the i386 PE targeted port of the linker and for ELF targeted ports. For i386 PE, symbols explicitly listed in a .def file are still exported, no matter what this option says. For ELF targeted ports, symbols affected by this option get treated as hidden.
--exclude-modules-for-implib module,module,...β a list of object files or archive members whose symbols should not be auto-exported, but which should be copied wholesale into the import library being generated during the link. Delimit with commas or colons, and the module names have to match exactly the filenameslduses to open the files. For archive members that's just the member name, but for object files the name you list must include and match precisely any path used to specify the input file on the linker's command-line. This one is available only for the i386 PE targeted port of the linker. And same as before: symbols explicitly listed in a.deffile are still exported regardless of this option. π«Ά-E,--export-dynamic,--no-export-dynamicβ when you're creating a dynamically linked executable,-Eor--export-dynamicmakes the linker add all symbols to the dynamic symbol table. The dynamic symbol table is the set of symbols visible from dynamic objects at run time. π
If you don't use either of those (or 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.
Here's the tea π΅: if you use dlopen to load a dynamic object that needs to refer back to symbols defined by the program β not by 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. Go read the description of --dynamic-list.
And note: this option is specific to ELF targeted ports. PE targets have a similar function for exporting all symbols from a DLL or EXE β check the description of --export-all-symbols below.
--export-dynamic-symbol=globβ when creating a dynamically linked executable, symbols matching glob get added to the dynamic symbol table. When creating a shared library, references to symbols matching glob will not be bound to the definitions within the shared library. And plot twist: this option is a total no-op when creating a shared library and-Bsymbolicor--dynamic-listaren't specified. It's only meaningful on ELF platforms that support shared libraries. π¦--export-dynamic-symbol-list=fileβ specify a--export-dynamic-symbolfor each pattern in file. The file's format is the same as the version node without scope and node name. See VERSION for more info.-EBβ link big-endian objects. This affects the default output format.-ELβ link little-endian objects. This affects the default output format.-f name,--auxiliary=nameβ when creating an ELF shared object, set the internalDT_AUXILIARYfield to name. This 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 say you later link a program against this filter object. When you run the program, the dynamic linker sees the DT_AUXILIARY field. If it resolves any symbols from the filter object, it first checks whether there's a definition in the shared object name. If there is one, that gets used instead of the definition in the filter object. And name doesn't even need to exist! Which means name can be used to provide an alternative implementation of certain functions β maybe for debugging, maybe for machine-specific performance. Iconic, honestly.
You can specify this option more than once, and the DT_AUXILIARY entries get created in the order they appear on the command line.
-F name,--filter=nameβ when creating an ELF shared object, set the internalDT_FILTERfield to 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. β¨
Later, if you link a program against this filter object and run it, the dynamic linker sees the DT_FILTER field. It resolves symbols according to the symbol table of the filter object as usual, but it actually links 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 name. Chef's kiss. π
Lowkey history lesson: 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 instead: 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. π
-fini=nameβ when creating an ELF executable or shared object, callNAMEwhen the executable or shared object is unloaded, by settingDT_FINIto the address of the function. By default, the linker uses_finias the function to call.-gβ ignored. Provided for compatibility with other tools. That's it, that's the whole option, bestie. π-G value,--gpsize=valueβ set the maximum size of objects to be optimized using the GP register to size. Only meaningful for object file formats like MIPS ELF that support putting large and small objects into different sections. Ignored for other object file formats.-h name,-soname=nameβ when creating an ELF shared object, set the internalDT_SONAMEfield to name. Then when an executable is linked with a shared object that has aDT_SONAMEfield, running that executable makes the dynamic linker attempt to load the shared object specified by theDT_SONAMEfield, rather than using the file name given to the linker. π-iβ perform an incremental link (same as option-r).-init=nameβ when creating an ELF executable or shared object, callNAMEwhen the executable or shared object is loaded, by settingDT_INITto the address of the function. By default, the linker uses_initas the function to call.-l namespec,--library=namespecβ add the archive or object file specified by namespec to the list of files to link. You can use this option any number of times. If namespec is of the form:filename,ldsearches the library path for a file called filename; otherwise it searches the library path for a file calledlibnamespec.a. π
On systems that support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld searches a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a .so extension means shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename.
The linker searches an archive only once, at the location where it's specified on the command line. If the archive defines a symbol that was undefined in some object appearing before the archive on the command line, the linker includes the appropriate file(s) from the archive. But an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again. That's just how it is. π
Need to force multiple searches? See the -( option.
You may list the same archive multiple times on the command line.
This type of archive searching is standard for Unix linkers. But 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 pathsldwill search for archive libraries andldcontrol scripts. Use it any number of times. Directories are searched in the order they're specified on the command line, and directories specified on the command line are searched before the default directories. All-Loptions apply to all-loptions, regardless of the order in which the options appear. And-Loptions do not affect howldsearches for a linker script unless the-Toption is specified. π§
If searchdir begins with = or $SYSROOT, then that prefix gets 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.
okay so bestie, you can also drop those paths inside a link script using the "SEARCH_DIR" command. And the search happens at the exact point where that linker script shows up in the command line. β¨
-memulation β Emulate the emulation linker. You can list the available emulations with the--verboseor-Voptions. If you don't use-m, the emulation is taken from theLDEMULATIONenvironment variable, if that's defined. Otherwise, the default emulation depends upon how the linker was configured. π-M,--print-mapβ Print a link map to the standard output. A link map gives you the tea on the link, including:- 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 Expressions for more information about expressions in linker scripts.
- How GNU properties are merged. When the linker merges input
.note.gnu.propertysections into one output.note.gnu.propertysection, some properties are removed or updated. These actions are reported in the link map. For example:
Removed property 0xc0000002 to merge foo.o (0x1) and bar.o (not found)
This indicates that property 0xc0000002 is removed from output when merging properties in foo.o, whose property 0xc0000002 value is 0x1, and bar.o, which doesn't have property 0xc0000002.
Updated property 0xc0010001 (0x1) to merge foo.o (0x1) and bar.o (0x1)
This indicates that property 0xc0010001 value is updated to 0x1 in output when merging properties in foo.o, whose 0xc0010001 property value is 0x1, and bar.o, whose 0xc0010001 property value is 0x1.
--print-map-discarded,--no-print-map-discardedβ Print (or do not print) the list of discarded and garbage collected sections in the link map. Enabled by default. ποΈ-n,--nmagicβ Turn off page alignment of sections, and disable linking against shared libraries. If the output format supports Unix style magic numbers, mark the output as"NMAGIC". π-N,--omagicβ Set the text and data sections to be readable and writable. Also, do not page-align the data segment, and disable linking against shared libraries. If the output format supports Unix style magic numbers, mark the output as"OMAGIC". Note: Although a writable text section is allowed for PE-COFF targets, it does not conform to the format specification published by Microsoft. π«--no-omagicβ This option negates most of the effects of the-Noption. It sets the text section to be read-only, and forces the data segment to be page-aligned. Note - this option does not enable linking against shared libraries. Use-Bdynamicfor this. π₯-ooutput,--output=output β Use output as the name for the program produced byld; if this option is not specified, the namea.outis used by default. The script command"OUTPUT"can also specify the output file name. π--dependency-file=depfile β Write a dependency file to depfile. This file contains a rule suitable for"make"describing the output file and all the input files that were read to produce it. The output is similar to the compiler's output with-M -MP. Note that there is no option like the compiler's-MM, to exclude "system files" (which is not a well-specified concept in the linker, unlike "system headers" in the compiler). So the output from--dependency-fileis always specific to the exact state of the installation where it was produced, and should not be copied into distributed makefiles without careful editing. π-Olevel β If level is a numeric values greater than zeroldoptimizes the output. This might take significantly longer and therefore probably should only be enabled for the final binary. At the moment this option only affects ELF shared library generation. Future releases of the linker may make more use of this option. Also currently there is no difference in the linker's behaviour for different non-zero values of this option. Again this may change with future releases. β‘-pluginname β Involve a plugin in the linking process. The name parameter is the absolute filename of the plugin. Usually this parameter is automatically added by the compiler, when using link time optimization, but users can also add their own plugins if they so wish. Note that the location of the compiler originated plugins is different from the place where thear,nmandranlibprograms search for their plugins. In order for those commands to make use of a compiler based plugin it must first be copied into the${libdir}/bfd-pluginsdirectory. Allgccbased linker plugins are backward compatible, so it is sufficient to just copy in the newest one. π--push-stateβ The--push-stateallows one to preserve the current state of the flags which govern the input file handling so that they can all be restored with one corresponding--pop-stateoption. The option which are 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 are specifications forpkg-config. When used with the--libsoption all possibly needed libraries are listed and then possibly linked with all the time. It is better to return something as follows:
-Wl,--push-state,--as-needed -libone -libtwo -Wl,--pop-state
--pop-stateβ Undoes the effect of--push-state, restores the previous values of the flags governing input file handling. β©οΈ-q,--emit-relocsβ Leave relocation sections and contents in fully linked executables. Post link analysis and optimization tools may need this information in order to perform correct modifications of executables. This results in larger executables. This option is currently only supported on ELF platforms. π§©--force-dynamicβ Force the output file to have dynamic sections. This option is specific to VxWorks targets. π₯-r,--relocatableβ Generate relocatable output---i.e., generate an output file that can in turn serve as input told. 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 this option is not specified, an absolute file is produced. When linking C++ programs, this option will not resolve references to constructors; to do that, use-Ur. When an input file does not have the same format as the output file, partial linking is only supported if that input file does not contain any relocations. Different output formats can have further restrictions; for example some"a.out"-based formats do not support partial linking with input files in other formats at all. This option does the same thing as-i. π-Rfilename,--just-symbols=filename β Read symbol names and their addresses from filename, but do not relocate it or include it in the output. This allows your output file to 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-Roption is followed by a directory name, rather than a file name, it is treated as the-rpathoption. π-s,--strip-allβ Omit all symbol information from the output file. βοΈ-S,--strip-debugβ Omit debugger symbol information (but not all symbols) from the output file. π--strip-discarded,--no-strip-discardedβ Omit (or do not omit) global symbols defined in discarded sections. Enabled by default. ποΈ-t,--traceβ Print the names of the input files asldprocesses them. If-tis given twice then members within archives are also printed.-toutput is useful to generate a list of all the object files and scripts involved in linking, for example, when packaging files for a linker bug report. π-Tscriptfile,--script=scriptfile β Use scriptfile as the linker script. This script replacesld's default linker script (rather than adding to it), socommandfilemust specify everything necessary to describe the output file. If scriptfile does not exist in the current directory,"ld"looks for it in the directories specified by any preceding-Loptions. Multiple-Toptions accumulate. π-dTscriptfile,--default-script=scriptfile β Use scriptfile as the default linker script. This option is similar to the--scriptoption except that processing of the script is delayed until after the rest of the command line has been processed. This allows options placed after the--default-scriptoption on the command line to affect the behaviour of the linker script, which can be important when the linker command line cannot be directly controlled by the user. (eg because the command line is being constructed by another tool, such asgcc). β³-usymbol,--undefined=symbol β okay so this one forces symbol to be entered in the output file as an undefined symbol π . Like, you're telling the linker "bestie, this name is a thing, trust me". Why would you want that? Because doing this may, for example, trigger linking of additional modules from standard libraries. And you can repeat-uover and over with different option arguments to enter even more undefined symbols. This option is equivalent to theEXTERNlinker script command, periodt.
If you're using this option to force extra modules to get pulled into the link, and it would be an error for the symbol to remain undefined, then you should use the option --require-defined instead. Noted. π
--require-defined=symbol β this demands that symbol is defined in the output file. It's the same as--undefinedexcept that if symbol is not defined in the output file then the linker will issue an error and exit π. Same effect can be achieved in a linker script by usingEXTERN,ASSERTandDEFINEDtogether. You can use this option multiple times to require additional symbols. Collect them all π.-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 told. When linking C++ programs,-Urdoes resolve references to constructors, unlike-r. It does not work to use-Uron files that were themselves linked with-Ur; once the constructor table has been built, it cannot be added to. So use-Uronly for the last partial link, and-rfor the others. Do not skip that part, bestie π«Ά.--orphan-handling=MODE β controls how orphan sections are handled. An orphan section is one not specifically mentioned in a linker script. Cute little foundlings.
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--uniquealso affects how sections are placed.discardβ all orphan sections are discarded, by placing them in the/DISCARD/section. bye felicia πwarnβ the linker will place the orphan section as forplaceand also issue a warning.errorβ the linker will exit with an error if any orphan section is found. dramatic, honestly.
The default if --orphan-handling is not 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. No merging, no blending, everyone gets their own lil space β¨.-v,--version,-Vβ display the version number forld. The-Voption also lists the supported emulations. Iconic behavior honestly π.-x,--discard-allβ delete all local symbols. poof π.-X,--discard-localsβ delete all temporary local symbols. (These symbols start with system-specific local label prefixes, typically.Lfor ELF systems orLfor traditionala.outsystems.) Very "who even are you" energy π.-ysymbol,--trace-symbol=symbol β print the name of each linked file in which symbol appears. This option may be given any number of times. On many systems it is necessary to prepend an underscore. This option is useful when you have an undefined symbol in your link but don't know where the reference is coming from. Literally the detective arc π.-Ypath β add path to the default library search path. This option exists for Solaris compatibility. That's it, that's the whole vibe.-zkeyword β the recognized keywords are:bndpltβ always generate BND prefix in PLT entries. Supported for Linux/x86_64.call-nop=prefix-addrcall-nop=suffix-nopcall-nop=prefix-bytecall-nop=suffix-byteβ specify the 1-byteNOPpadding when transforming indirect call to a locally defined function,foo, via its GOT slot.call-nop=prefix-addrgenerates0x67 call foo.call-nop=suffix-nopgeneratescall foo 0x90.call-nop=prefix-bytegeneratesbyte call foo.call-nop=suffix-bytegeneratescall foo byte. Supported for i386 and x86_64.cet-report=nonecet-report=warningcet-report=errorβ specify how to report the missingGNU_PROPERTY_X86_FEATURE_1_IBTandGNU_PROPERTY_X86_FEATURE_1_SHSTKproperties in input.note.gnu.propertysection.cet-report=none, which is the default, will make the linker not report missing properties in input files.cet-report=warningwill make the linker issue a warning for missing properties in input files.cet-report=errorwill make the linker issue an error for missing properties in input files. Note thatibtwill turn off the missingGNU_PROPERTY_X86_FEATURE_1_IBTproperty report andshstkwill turn off the missingGNU_PROPERTY_X86_FEATURE_1_SHSTKproperty report. Supported for Linux/i386 and Linux/x86_64.combrelocnocombrelocβ combine multiple dynamic relocation sections and sort to improve dynamic symbol lookup caching. Do not do this ifnocombreloc. pick a lane bestie.commonnocommonβ generate common symbols withSTT_COMMONtype during a relocatable link. UseSTT_OBJECTtype ifnocommon.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-weaknodynamic-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 ifnodynamic-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. sharing is caring π«Ά.globalauditβ this option is only meaningful when building a dynamic executable. This option marks the executable as requiring global auditing by setting theDF_1_GLOBAUDITbit in theDT_FLAGS_1dynamic tag. Global auditing requires that any auditing library defined via the--depauditor-Pcommand-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β generateGNU_PROPERTY_X86_FEATURE_1_IBTin.note.gnu.propertysection to indicate compatibility with IBT. This also impliesibtplt. 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. first in, last out, main character energy π.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. relatable tbh π.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. chaos permitted β¨.nocopyrelocβ disable linker generated.dynbssvariables 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 todlopen.nodumpβ specify that the object can not be dumped bydldump.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. no waiting, we go now πββοΈ.originβ specify that the object requires$ORIGINhandling in paths.
relro/norelroβ bestie, this one builds an ELFPT_GNU_RELROsegment header into the object, which says "hey, this memory segment should go read-only after relocation" β if the platform supports it, that is. π But heads up: if you setcommon-page-sizesmaller than the actual system page size, this protection is basically giving nothing, it's useless. Andnorelromeans noPT_GNU_RELROsegment gets made at all, periodt.separate-code/noseparate-codeβ makes a separate codePT_LOADsegment header in the object. Translation: a memory segment that holds only instructions and lives in completely disjoint pages from literally any other data. β¨ No mixing. If you saynoseparate-code, no separate codePT_LOADsegment for you, sorry babe.shstkβ generatesGNU_PROPERTY_X86_FEATURE_1_SHSTKin the.note.gnu.propertysection to flex compatibility with Intel Shadow Stack. π¦ Supported for Linux/i386 and Linux/x86_64, so iykyk.stack-size=valueβ sets a stack size for an ELFPT_GNU_STACKsegment. If you pass zero? That overrides any default non-zero sizedPT_GNU_STACKsegment creation. Yes really. πstart-stop-visibility=valueβ picks the ELF symbol visibility for the synthesized__start_SECNAMEand__stop_SECNAMEsymbols.valuehas to be exactly one ofdefault,internal,hidden, orprotectedβ no vibes-based spelling, bestie. If you never pass a-z start-stop-visibilityoption, thenprotectedgets used, for compatibility with historical practice. But β and this is the part that matters β it's highly recommended that you use-z start-stop-visibility=hiddenin new programs and shared libraries so these symbols don't get exported between shared objects, which is not usually what anyone intended. πtext/notext/textoffβ report an error ifDT_TEXTRELis set, meaning the position-independent or shared object has dynamic relocations hanging out in read-only sections. π Don't report an error if you usednotextortextoff.undefsβ don't report unresolved symbol references from regular object files, whether you're making an executable or making a shared library. This option is the inverse of-z defs.
Other keywords are ignored for Solaris compatibility.
-(archives-),--start-grouparchives--end-groupβ archives should be a list of archive files, and they can be either explicit file names or-loptions. π
The archives you named get searched repeatedly until no new undefined references show up. Normally an archive only gets searched once, in the order you typed it on the command line. So 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 just not be able to resolve that reference. π By grouping the archives, they all get searched over and over until all possible references are resolved.
Real talk: using this option has a significant performance cost. It's best to only reach for it when there are unavoidable circular references between two or more archives. Not a casual flex.
--accept-unknown-input-arch/--no-accept-unknown-input-archβ tells the linker to accept input files whose architecture can't be recognised. The whole assumption here is that the user knows what they're doing and deliberately wants to link in these unknown input files. π«Ά This was actually the default behaviour of the linker before release 2.14. From release 2.14 onwards the default is to reject such input files, so--accept-unknown-input-archwas added to bring the old behaviour back.--as-needed/--no-as-neededβ this one affects ELFDT_NEEDEDtags for dynamic libraries mentioned on the command line after the--as-neededoption. Normally the linker adds aDT_NEEDEDtag for each dynamic library on the command line, regardless of whether the library is actually needed or not.--as-neededmakes aDT_NEEDEDtag get emitted only 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 isn't found in theDT_NEEDEDlists 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 don't affect whether the library is seen as needed. This is similar to the rules for extraction of object files from archives.--no-as-neededrestores the default behaviour. β¨--add-needed/--no-add-neededβ these two have been deprecated, because their names are way too similar to--as-neededand--no-as-neededand that was chaos. π They've been replaced by--copy-dt-needed-entriesand--no-copy-dt-needed-entries.-assertkeyword β this option is ignored for SunOS compatibility. Nothing more, it's just sitting there.-Bdynamic,-dy,-call_sharedβ link against dynamic libraries. This is only meaningful on platforms where shared libraries are supported. On such platforms this option is normally the default. 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-loptions that follow it.-Bgroupβ sets theDF_1_GROUPflag in theDT_FLAGS_1entry in the dynamic section. This makes the runtime linker handle lookups in this object and its dependencies only inside the group.--unresolved-symbols=report-allis implied. This option is only meaningful on ELF platforms which support shared libraries.-Bstatic,-dn,-non_shared,-staticβ do not link against shared libraries. Only meaningful on platforms where shared libraries are supported. Again, the different variants are for compatibility with various systems. You can use this option multiple times on the command line: it affects library searching for-loptions that follow it. This option also implies--unresolved-symbols=report-all. And yes, it can be used with-sharedβ doing so means a shared library is being created, but all of that 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 there is one. Normally it's possible for a program linked against a shared library to override the definition within the shared library. This option is only meaningful on ELF platforms which support shared libraries.-Bsymbolic-functionsβ same energy, but for global function symbols: when creating a shared library, bind references to global function symbols to the definition within the shared library, if there is one. Only meaningful on ELF platforms which support shared libraries.--dynamic-list=dynamic-list-fileβ hands the linker the name of a dynamic list file. 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 which 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. All of them. π«Ά--dynamic-list-cpp-newβ provides the builtin dynamic list for C++operator newanddelete. Mainly useful for building sharedlibstdc++.--dynamic-list-cpp-typeinfoβ provides the builtin dynamic list for C++ runtime type identification.--check-sections/--no-check-sectionsβ asks the linker not to check section addresses after they've been assigned, to see if there are any overlaps. Normally the linker does perform this check, and if it finds overlaps it produces suitable error messages. The linker does know about sections in overlays, and does make allowances for them. Default behaviour comes back with--check-sections. Also: section overlap isn't usually checked for relocatable links β you can force checking in that case with--check-sections.--copy-dt-needed-entries/--no-copy-dt-needed-entriesβ this affects how dynamic libraries referred to byDT_NEEDEDtags inside ELF dynamic libraries mentioned on the command line get treated. Normally the linker won't add aDT_NEEDEDtag to the output binary for each library mentioned in aDT_NEEDEDtag in an input dynamic library. But with--copy-dt-needed-entrieson the command line, any dynamic libraries that follow it will have theirDT_NEEDEDentries added. Default behaviour is restored with--no-copy-dt-needed-entries.
This option also changes how symbols in dynamic libraries get resolved. With --copy-dt-needed-entries, dynamic libraries mentioned on the command line get recursively searched, following their DT_NEEDED tags to other libraries, to resolve symbols required by the output binary. With the default setting, searching of dynamic libraries that follow it stops with the dynamic library itself. No DT_NEEDED links get traversed to resolve symbols. π
--crefβ output a cross reference table. If a linker map file is being generated, the cross reference table gets printed to the map file. Otherwise, it's printed on standard output. π
The format of the table is intentionally simple, so it can be easily processed by a script if necessary. The symbols are printed out, sorted by name. 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β this option inhibits the assignment of addresses to common symbols. The script commandINHIBIT_COMMON_ALLOCATIONhas the same effect. β¨--no-define-commonβ bestie, this one lets you decouple the whole "should we assign addresses to Common symbols" question from what kind of output file you're making β¨ Normally a non-Relocatable output type just forces address assignment onto Common symbols, no discussion. But with--no-define-common, Common symbols that get referenced from a shared library can be assigned addresses only in the main program π That kills the unused duplicate space in the shared library, and also prevents any possible confusion about resolving to the wrong duplicate when you've got a whole swarm of dynamic modules with specialized search paths for runtime symbol resolution. No cap.--force-group-allocationβ this makes the linker place section group members like normal input sections and delete the section groups entirely πΈ For a final link that's already the default behaviour, but you can use this option to change how a relocatable link (-r) behaves. The script command"FORCE_GROUP_ALLOCATION"does the exact same thing. Iconic.--defsym=symbol=expressionβ makes a global symbol in the output file holding the absolute address given by expression β You can use this option as many times as you want to define multiple symbols on the command line. Only a limited form of arithmetic works here: a hexadecimal constant, the name of an existing symbol, or+and-to add or subtract hexadecimal constants or symbols. If your expression needs to be more elaborate than that, consider using the linker command language from a script instead.
π¨ PSA: there should be no white space between symbol, the equals sign ("="), and expression. Not even one. I'm serious.
--demangle[=style],--no-demangleβ these control whether symbol names get demangled in error messages and other output π When the linker is told to demangle, it tries to present symbol names in a readable fashion: 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, so the optional demangling style argument lets you pick the right one for your compiler. The linker demangles by default unless the environment variableCOLLECT_NO_DEMANGLEis set. These options can override that default. Periodt.-Ifile,--dynamic-linker=fileβ sets the name of the dynamic linker π Only meaningful when you're generating dynamically linked ELF executables. The default dynamic linker is normally correct, so like... don't use this unless you genuinely know what you're doing. π--no-dynamic-linkerβ when producing an executable file, omit the request for a dynamic linker to be used at load-time π Only meaningful for ELF executables that contain dynamic relocations, and it usually requires entry point code capable of processing those relocations. So, y'know, know what you're signing up for.--embedded-relocsβ similar to the--emit-relocsoption, except the relocs get stored in a target-specific section π¦ Only supported by theBFIN,CR16andM68Ktargets. iykyk.--disable-multiple-abs-defsβ do not allow multiple definitions with symbols included in filename invoked by-Ror--just-symbolsβ--fatal-warnings,--no-fatal-warningsβ treat all warnings as errors π The default behaviour can be restored with--no-fatal-warnings.--force-exe-suffixβ make sure an output file has a.exesuffix π If a successfully built fully linked output file does not have a".exe"or".dll"suffix, this option forces the linker to copy the output file to one of the same name with a".exe"suffix. Super useful when you're 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. The way Windows just refuses... π--gc-sections,--no-gc-sectionsβ enable garbage collection of unused input sections π₯ It's ignored on targets that don't support it. The default behaviour (not doing this garbage collection) can be restored by specifying--no-gc-sectionson the command line. Note that garbage collection forCOFFandPEformat targets is supported, but the implementation is currently considered experimental β so, caution bestie.
--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 has been determined, the linker recursively marks as used any section referenced by their relocations. See --entry, --undefined, and --gc-keep-exported.
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 one of the options --entry, --undefined, or --gc-keep-exported, or by a "ENTRY" command in the linker script.
--print-gc-sections,--no-print-gc-sectionsβ list all sections removed by garbage collection π The listing is printed onstderr. Only effective if garbage collection has been enabled via the--gc-sectionsoption. The default behaviour (not listing the sections that get removed) can be restored by specifying--no-print-gc-sectionson the command line.--gc-keep-exportedβ when--gc-sectionsis enabled, this prevents garbage collection of unused input sections that contain global symbols having default or protected visibility π Intended for executables where unreferenced sections would otherwise be garbage collected regardless of the external visibility of contained symbols. Note that this option has no effect when linking shared objects, since that's already the default behaviour there. Only supported for ELF format targets.--print-output-formatβ print the name of the default output format (maybe influenced by other command-line options) β¨ This is the string that would appear in an"OUTPUT_FORMAT"linker script command.--print-memory-usageβ print used size, total size and used size of memory regions created with theMEMORYcommand πΈ Super useful on embedded targets to get a quick view of how much free memory you've got. The output format has one headline and one line per region, and it's both human readable and easily parsable by tools. Here's an example of an output:
Memory region Used Size Region Size %age Used
ROM: 256 KB 1 MB 25.00%
RAM: 32 B 2 GB 0.00%
--helpβ print a summary of the command-line options on the standard output and exit π--target-helpβ print a summary of all target-specific options on the standard output and exit π-Map=mapfileβ print a link map to the file mapfile π See the description of the-Moption, above. Specifying a directory as mapfile causes the linker map to be written into a file inside the directory β the name of the file is based upon the output filename with".map"appended. Cute, right?--no-keep-memoryβldnormally optimizes for speed over memory usage by caching the symbol tables of input files in memory π§ This option tellsldto instead optimize for memory usage, by rereading the symbol tables as necessary. This may be required ifldruns out of memory space while linking a large executable. π--no-undefined,-z defsβ report unresolved symbol references from regular object files π₯ This is done even if the linker is creating a non-symbolic shared library. The switch--[no-]allow-shlib-undefinedcontrols the behaviour for reporting unresolved references found in shared libraries being linked in.
The effects of this option can be reverted by using "-z undefs".
--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 used.--allow-shlib-undefined,--no-allow-shlib-undefinedβ allows or disallows undefined symbols in shared libraries π Similar to--no-undefined, except it determines 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.
--no-undefined-versionβ normally when a symbol has an undefined version, the linker ignores it π This option disallows symbols with undefined version, and a fatal error will be issued instead.--default-symverβ create and use a default symbol version (the soname) for unversioned exported symbols β--default-imported-symverβ create and use a default symbol version (the soname) for unversioned imported symbols π--no-warn-mismatchβ okay so normally ld will straight up yell at you if you try to link input files that don't match for some reason β like they were compiled for different processors or different endiannesses π. This option tells ld to justβ¦ silently permit those possible errors. Use it with care only, like in cases where you've taken some special action that already ensures the linker errors are inappropriate. It's giving "I know what I'm doing" energy and you better actually know what you're doing, bestie.--no-warn-search-mismatchβ normally ld gives you a warning if it finds an incompatible library during a library search. This one silences the warning. π€«--no-whole-archiveβ turns off the effect of the--whole-archiveoption for the archive files that come after it. Undoing the thing, iconic.--noinhibit-execβ keeps the executable output file whenever it's still usable π«Ά. Normally the linker will not produce an output file if it hits errors during the link process β it exits without writing an output file when it issues any error whatsoever. This flag is like "no babe keep going, I still want the file."-nostdlibβ only search library directories that were explicitly specified on the command line. Library directories specified in linker scripts (including linker scripts specified on the command line) get ignored. Periodt.--oformat=output-formatβ ld may be configured to support more than one kind of object file. If your ld is configured that way, you can use--oformatto specify the binary format for the output object file. But ngl, even when ld supports alternative object formats, you usually don't need to specify this, because ld should be configured to produce the most usual format on each machine as its default output format.output-formatis a text string, the name of a particular format supported by the BFD libraries. (You can list the available binary formats withobjdump -i.) β¨ The script commandOUTPUT_FORMATcan also specify the output format, but this option overrides it. Queen behaviour.--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.aor*.afor 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.dlltoolfor DLLs). This option is only available for the i386 PE and ELF targeted ports of the linker. π-pie,--pic-executableβ create a position independent executable π¦. This is 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. That's it, that's the whole vibe π.-Qyβ this option is ignored for SVR4 compatibility. Same energy.--relax,--no-relaxβ an option with machine dependent effects. This option is only supported on a few targets.- On some platforms the
--relaxoption 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. β¨ - 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,
--relaxis accepted, but ignored. - On platforms where
--relaxis accepted the option--no-relaxcan be used to disable the feature.
- On some platforms the
--retain-symbols-file=filenameβ retain 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-filedoes not discard undefined symbols, or symbols needed for relocations.- You may only specify
--retain-symbols-fileonce in the command line. It overrides-sand-S.
-rpath=dirβ add a directory to the runtime library search path π. This is used when linking an ELF executable with shared objects. All-rpatharguments are concatenated and passed to the runtime linker, which uses them to locate shared objects at runtime.- The
-rpathoption is also used when locating shared objects which are needed by shared objects explicitly included in the link; see the description of the-rpath-linkoption. Searching-rpathin this way is only supported by native linkers and cross linkers which have been configured with the--with-sysrootoption. - If
-rpathis not used when linking an ELF executable, the contents of the environment variableLD_RUN_PATHwill be used if it is defined. - The
-rpathoption may also be used on SunOS. By default, on SunOS, the linker will form a runtime search path out of all the-Loptions it is given. If a-rpathoption is used, the runtime search path will be formed exclusively using the-rpathoptions, ignoring the-Loptions. This can be useful when usinggcc, which adds many-Loptions which may be on NFS mounted file systems. - For compatibility with other ELF linkers, if the
-Roption is followed by a directory name, rather than a file name, it is treated as the-rpathoption.
- The
-rpath-link=dirβ when using ELF or SunOS, one shared library may require another π. This happens when anld -sharedlink includes a shared library as one of the input files.- When the linker encounters such a dependency when doing a non-shared, non-relocatable link, it will automatically try to locate the required shared library and include it in the link, if it's not included explicitly. In such a case, the
-rpath-linkoption specifies the first set of directories to search. The-rpath-linkoption may specify a sequence of directory names either by specifying a list of names separated by colons, or by appearing multiple times. - The tokens
$ORIGINand$LIBcan appear in these search directories. They will be replaced by the full path to the directory containing the program or shared object in the case of$ORIGINand eitherlibβ for 32-bit binaries β orlib64β for 64-bit binaries β in the case of$LIB. - The alternative form of these tokens β
${ORIGIN}and${LIB}β can also be used. The token$PLATFORMis not supported. - > β οΈ This option should be used with caution as it overrides the search path that may have been hard compiled into a shared library. In such a case it is possible to use unintentionally a different search path than the runtime linker would do. π
- The linker uses the following search paths to locate required shared libraries:
- Any directories specified by
-rpath-linkoptions. - Any directories specified by
-rpathoptions. The difference between-rpathand-rpath-linkis that directories specified by-rpathoptions are included in the executable and used at runtime, whereas the-rpath-linkoption is only effective at link time. Searching-rpathin this way is only supported by native linkers and cross linkers which have been configured with the--with-sysrootoption. - On an ELF system, for native linkers, if the
-rpathand-rpath-linkoptions were not used, search the contents of the environment variableLD_RUN_PATH. - On SunOS, if the
-rpathoption was not used, search any directories specified using-Loptions. - For a native linker, search the contents of the environment variable
LD_LIBRARY_PATH. - For a native ELF linker, the directories in
DT_RUNPATHorDT_RPATHof a shared library are searched for shared libraries needed by it. TheDT_RPATHentries are ignored ifDT_RUNPATHentries exist. - The default directories, normally
/liband/usr/lib. - For a linker for a Linux system, if the file
/etc/ld.so.confexists, the list of directories found in that file. Note: the path to this file is prefixed with thesysrootvalue, if that is defined, and then anyprefixstring if the linker was configured with the--prefix=<path>option. - For a native linker on a FreeBSD system, any directories specified by the
_PATH_ELF_HINTSmacro defined in theelf-hints.hheader file. - Any directories specified by a
SEARCH_DIRcommand in the linker script being used.
- Any directories specified by
- If the required shared library is not found, the linker will issue a warning and continue with the link.
- When the linker encounters such a dependency when doing a non-shared, non-relocatable link, it will automatically try to locate the required shared library and include it in the link, if it's not included explicitly. In such a case, the
-shared,-Bshareableβ create a shared library π. This is currently only supported on ELF, XCOFF and SunOS platforms. On SunOS, the linker will automatically create a shared library if the-eoption is not used and there are undefined symbols in the link.--sort-common,--sort-common=ascending,--sort-common=descendingβ this option 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 considered are sixteen-byte or larger, eight-byte, four-byte, two-byte, and one-byte. This is to prevent gaps between symbols due to alignment constraints β¨. If no sorting order is specified, then descending order is assumed.--sort-section=nameβ this option will applySORT_BY_NAMEto all wildcard section patterns in the linker script. Clean, organised, main character energy.--sort-section=alignmentβ this option will applySORT_BY_ALIGNMENTto all wildcard section patterns in the linker script.--spare-dynamic-tags=countβ this option specifies the number of empty slots to leave in the.dynamicsection of ELF shared objects. Empty slots may be needed by post processing tools, such as the prelinker π§. The default is5.--split-by-file[=size]β similar to--split-by-relocbut creates a new output section for each input file when size is reached. size defaults to a size of1if not given. π¦--split-by-reloc[=count]β okay so this one is for when your output file is getting embarrassingly THICC π It tries to create extra sections in the output file so that no single output section in the file ends up holding more than count relocations. Which sounds niche until you remember that COFF literally cannot represent more than 65535 relocations in a single section β so if you're generating huge relocatable files to download into certain real time kernels with the COFF object file format, this is your girl. Heads up tho: this will fail to work with object file formats that don't support arbitrary sections. And the linker will not split up individual input sections for redistribution β so if one single input section has more than count relocations in it, one output section is just gonna sit there holding all of them, no cap. count defaults to32768.--statsβ compute and display statistics about the operation of the linker, like execution time and memory usage. It's giving "let me see the receipts" β¨--sysroot=directoryβ use directory as the location of the sysroot, overriding the configure-time default. Small print bestie: this option is only supported by linkers that were configured using--with-sysroot.--task-linkβ this is used by COFF/PE based targets to create a task-linked object file where all of the global symbols have been converted to statics. very specific, very demure π--traditional-formatβ for some targets, the output ofldis different in some ways from the output of some existing linker. This switch requestsldto use the traditional format instead.
For example, on SunOS, ld combines duplicate entries in the symbol string table. This can reduce the size of an output file with full debugging information by over 30 percent. Unfortunately, the SunOS "dbx" program can not read the resulting program ("gdb" has no trouble). The --traditional-format switch tells ld to not combine duplicate entries.
--section-start=sectionname=orgβ locate a section in the output file at the absolute address given by org. You may use this option as many times as necessary to locate multiple sections in the command line. org must be a single hexadecimal integer; for compatibility with other linkers, you may omit the leading0xusually associated with hexadecimal values. Note: there should be no white space between sectionname, the equals sign ("="), and org. fr fr, not even one space, she will not forgive you π-Tbss=org-Tdata=org-Ttext=orgβ same as--section-start, with".bss",".data"or".text"as the sectionname. three for the price of one, we love a bundle π-Ttext-segment=orgβ when creating an ELF executable, it will set the address of the first byte of the text segment. segment, not section, bestie, don't mix them up β¨-Trodata-segment=orgβ when creating an ELF executable or shared object for a target where the read-only data is in its own segment separate from the executable text, it will set the address of the first byte of the read-only data segment. only when the target's built that way, otherwise she's just vibing-Tldata-segment=orgβ when creating an ELF executable or shared object for x86-64 medium memory model, it will set the address of the first byte of the ldata segment. x86-64 medium memory model girlies, this one's for you π--unresolved-symbols=methodβ determine how to handle unresolved symbols. There are four possible values for method:ignore-allβ do not report any unresolved symbols. blissful ignorance, iconicreport-allβ report all unresolved symbols. This is the default. πignore-in-object-filesβ report unresolved symbols that are 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. This can be useful when creating a dynamic binary and it is known that all the shared libraries that it should be referencing are included 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 will generate an error message for each reported unresolved symbol but the option --warn-unresolved-symbols can change this to a warning. softer delivery, same tea π
--dll-verbose--verbose[=NUMBER]β display the version number forldand list the linker emulations supported. Display which input files can and cannot be opened. Display the linker script being used by the linker. If the optional NUMBER argument> 1, plugin symbol status will also be displayed. turn the volume all the way up, she'll tell you everything π₯--version-script=version-scriptfileβ specify the name of a version script to the linker. This is typically used when creating shared libraries to specify additional information about the version hierarchy for the library being created. Small print: this option is only fully supported on ELF platforms which support shared libraries; see VERSION. It is 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 will not be exported. sneaky little visibility filter, we love her π¦--warn-commonβ warn when a common symbol is combined with another common symbol or with a symbol definition. Unix linkers allow this somewhat sloppy practice, but linkers on some other operating systems do not. This option allows you to find potential problems from combining global symbols. Unfortunately, some C libraries use this practice, so you may get some warnings about symbols in the libraries as well as in your programs. not your fault bestie, the library did this π
There are three kinds of global symbols, illustrated here by 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 does not 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. If they are of different sizes, it picks the largest size. The linker turns a common symbol into a declaration, if there is a definition of the same variable.
The --warn-common option can produce five kinds of warnings. Each warning consists of a pair of lines: the first describes the symbol just encountered, and the second describes the previous symbol encountered with the same name. One or both of the two symbols will be a common symbol.
- Turning a common symbol into a reference, because there is already a definition for the symbol.
<file>(<section>): warning: common of `<symbol>'
overridden by definition
<file>(<section>): warning: defined here
- Turning a common symbol into a reference, because a later definition for the symbol is encountered. This is the same as the previous case, except that the symbols are encountered in a different order.
<file>(<section>): warning: definition of `<symbol>'
overriding common
<file>(<section>): warning: common is here
- Merging a common symbol with a previous same-sized common symbol.
<file>(<section>): warning: multiple common
of `<symbol>'
<file>(<section>): warning: previous common is here
- Merging a common symbol with a previous larger common symbol.
<file>(<section>): warning: common of `<symbol>'
overridden by larger common
<file>(<section>): warning: larger common is here
- Merging a common symbol with a previous smaller common symbol. This is the same as the previous case, except that the symbols are encountered in a different order.
<file>(<section>): warning: common of `<symbol>'
overriding smaller common
<file>(<section>): warning: smaller common is here
--warn-constructorsβ warn if any global constructors are used. This is only useful for a few object file formats. For formats like COFF or ELF, the linker can not detect the use of global constructors. so like, she physically cannot see them, don't @ her π--warn-multiple-gpβ warn if multiple global pointer values are required in the output file. This is only meaningful for certain processors, such as the Alpha. Specifically, some processors put large-valued constants in a special section. A special register (the global pointer) points into the middle of this section, so that constants can be loaded efficiently via a base-register relative addressing mode. Since the offset in base-register relative mode is fixed and relatively small (e.g.,16bits), this limits the maximum size of the constant pool. Thus, in large programs, it is often necessary to use multiple global pointer values in order to be able to address all possible constants. This option causes a warning to be issued whenever this case occurs. the Alpha girlies know exactly what this is about π--warn-onceβ only warn once for each undefined symbol, rather than once per module which refers to it. say it once and let it go, we're not doing repetition β¨--warn-section-alignβ warn if the address of an output section is changed because of alignment. Typically, the alignment will be set by an input section. The address will only be changed if it not explicitly specified; that is, if the"SECTIONS"command does not specify a start address for the section. so if you never set a start address, she's allowed to slide it around π--warn-textrelβ warn if the linker addsDT_TEXTRELto a position-independent executable or shared object. that's a whole situation, so yeah, warning π₯--warn-alternate-emβ warn if an object has alternate ELF machine code. rare, mysterious, kind of iconic π¦--warn-unresolved-symbolsβ if the linker is going to report an unresolved symbol (see the option--unresolved-symbols) it will normally generate an error. This option makes it generate a warning instead. same message, gentler tone π--error-unresolved-symbolsβ this restores the linker's default behaviour of generating errors when it is reporting unresolved symbols. put the stern voice back on, periodt--whole-archiveβ for each archive mentioned on the command line after the--whole-archiveoption, include every object file in the archive in the link, rather than searching the archive for the required object files. This is normally used to turn an archive file into a shared library, forcing every object to be included in the resulting shared library. This option may be used more than once. she takes everyone, no auditions, no cuts π
okay bestie, real talk about using this one from gcc β two things, and you WILL forget them, so imma say them loud:
- First:
gccliterally does not know this option exists, so you have to smuggle it in as-Wl,-whole-archive. That's the whole vibe. No cap. - Second: do NOT forget to use
-Wl,-no-whole-archiveafter your lil list of archives, becausegccis gonna add its own list of archives to your link and you probs do not want this flag to be affecting those too. π
--wrap=symbolβ this one is iconic, genuinely. It puts a wrapper function around symbol. Any undefined reference to symbol gets resolved to__wrap_symbolinstead. And any undefined reference to__real_symbolgets resolved to symbol. It's giving β¨ middle-man energy β¨ and we love her.
So basically you can wrap a system function. Your wrapper function should be called __wrap_symbol. And if it wants to call the actual system function, it just calls __real_symbol. Easy.
Here's a trivial lil example, serve it up:
void *
__wrap_malloc (size_t c)
{
printf ("malloc called with %zu\n", c);
return __real_malloc (c);
}
So if you link other code with this file using --wrap malloc, then every single call to malloc will call __wrap_malloc instead. And the call to __real_malloc inside __wrap_malloc? That one calls the real malloc. Perfect, no notes. π
You may also wanna provide a __real_malloc function as well, so that links without the --wrap option will still succeed. BUT β and this is important, bestie β if you do this, you should 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. Rude of it tbh.
Also: only undefined references get replaced by the linker. So translation unit internal references to symbol are NOT resolved to __wrap_symbol. Watch this next example β the call to f inside g does not get resolved to __wrap_f. Not even a little bit.
int
f (void)
{
return 123;
}
int
g (void)
{
return f();
}
--eh-frame-hdr--no-eh-frame-hdrβ request (--eh-frame-hdr) or suppress (--no-eh-frame-hdr) the creation of the.eh_frame_hdrsection and the ELFPT_GNU_EH_FRAMEsegment header. Request it or don't, your call, main character. π¦--no-ld-generated-unwind-infoβ requests the creation of.eh_frameunwind info for linker-generated code sections like PLT. This one is on by default if linker-generated unwind info is supported. Yeah, default-on, she's confident. πββοΈ--enable-new-dtags--disable-new-dtagsβ so this linker can create the new dynamic tags in ELF. But the older ELF systems might not understand them, which is lowkey a problem. If you say--enable-new-dtags, the new dynamic tags get created as needed and the older dynamic tags get omitted. If you say--disable-new-dtags, no new dynamic tags get created at all. By default, the new dynamic tags are not created. And heads up: these options are only available for ELF systems. ELF girlies only. π--hash-size=numberβ sets the default size of the linker's hash tables to a prime number close to number. Bump this value up and the linker might take less time doing its tasks β but it costs you more memory for the linker. Reduce the value and you save memory but pay in speed. Classic tradeoff, it's giving ~balance~ βοΈ--hash-style=styleβ sets the type of the linker's hash table(s). style can be:sysvβ for the classic ELF.hashsectiongnuβ for the new style GNU.gnu.hashsectionbothβ for both the classic ELF.hashand the new style GNU.gnu.hashhash tables
The default depends on how the linker was configured, but for most Linux based systems it'll be both. Periodt. π
--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 using zlib. Let's break it down, bestie:--compress-debug-sections=noneβ doesn't compress DWARF debug sections at all. Chill.--compress-debug-sections=zlib-gnuβ compresses DWARF debug sections and renames them to begin with.zdebuginstead of.debug.--compress-debug-sections=zlib-gabiβ also compresses DWARF debug sections, but instead of renaming them, it sets theSHF_COMPRESSEDflag in the sections' headers.
And --compress-debug-sections=zlib is just an alias for --compress-debug-sections=zlib-gabi. Same thing, different name, we stan an alias. π
Heads up: 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 the input files will be uncompressed before they get copied into the output binary. It's giving "no compression, I said what I said."
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. Go check, it's right there. π
--reduce-memory-overheadsβ this reduces memory requirements atldruntime, at the expense of linking speed. It was introduced to select the oldO(n^2)algorithm for link map file generation, rather than the newO(n)algorithm which uses about 40% more memory for symbol storage. So yeah, it's the old-school algorithm, but make it memory-friendly.
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. BUT β this is not done if the --hash-size switch has been used. So --hash-size wins that argument, respectfully. π
And plot twist: the --reduce-memory-overheads switch may also be used to enable other tradeoffs in future versions of the linker. Future tea, we'll see. π΅
--build-id--build-id=styleβ requests the creation of a.note.gnu.build-idELF note section or a.buildidCOFF section. The contents of the note are unique bits identifying this linked file. style can be:uuidβ to use 128 random bitssha1β to use a 160-bit SHA1 hash on the normative parts of the output contentsmd5β to use a 128-bit MD5 hash on the normative parts of the output contents0xhexstringβ 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. Default queen. π
The md5 and sha1 styles produce an identifier that is 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 β so don't do that, bestie. A linked file may be changed later by other tools, but the build ID bit string identifying the original linked file does not change. She's committed. π«Ά
Passing none for style disables the setting from any --build-id options earlier on the command line. Bye to all of that. π
<h2>β¨ the i386 PE linker era β¨</h2>
The i386 PE linker supports the -shared option, which causes the output to be a dynamically linked library (DLL) instead of a normal executable. You should name the output *.dll when you use this option. Please. Name it right. π
In addition, the linker fully supports the standard *.def files, which may be specified on the linker command line like an object file. And actually, it should precede archives it exports symbols from, to ensure that they get linked in, just like a normal object file. Order matters, bestie, always has. β¨
In addition to the options common to all targets, the i386 PE linker supports additional command-line options that are specific to the i386 PE target. And fun fact: options that take values may be separated from their values by either a space or an equals sign. Either/or, she's flexible. πΈ
--add-stdcall-aliasβ if given, symbols with a stdcall suffix (@nn) will be exported as-is and also with the suffix stripped. Double the export, double the fun. [This option is specific to the i386 PE targeted port of the linker]--base-file fileβ use file as the name of a file in which to save the base addresses of all the relocations needed for generating DLLs withdlltool. [This is an i386 PE specific option]--dllβ creates a DLL instead of a regular executable. You may also use-sharedor specify aLIBRARYin a given.deffile. Three paths, one destiny. [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 permits the use of section names longer than eight characters, which is the normal limit for COFF. By default, these names are only allowed in object files, because fully-linked executable images don't carry the COFF string table required to support the longer names.
But as a GNU extension, it's possible to allow their use in executable images as well β or to (probably pointlessly!) disallow it in object files β by using these two options. Executable images generated with these long section names are slightly non-standard, carrying as they do a string table, and may generate confusing output when examined with non-GNU PE-aware tools, like file viewers and dumpers. π΅βπ«
However β and this is the twist β GDB relies on the use of 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 the presence of debug information while linking an executable image and not stripping symbols. She's breaking the rules for GDB, and honestly? Fair. [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 cannot resolve, it'll attempt to do "fuzzy linking" by looking for another defined symbol that differs only in the format of the symbol name (cdecl vs stdcall) and will resolve that symbol by linking to the match. It's giving matchmaker energy. π
For 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 may need this feature to be usable. So it's a necessary evil, kinda. π
If you specify --enable-stdcall-fixup, this feature is fully enabled and warnings are not printed. If you specify --disable-stdcall-fixup, this feature is disabled and such mismatches are considered to be errors. Choose wisely, bestie. [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 it's possible to disable/enable that default underscore symbol-prefix. Underscore on, underscore off, she contains multitudes. π--export-all-symbolsβ okay so bestie, if you pass this, every single global symbol in the objects used to build a DLL gets exported by that DLL. π
Lowkey important: this is already the default if there otherwise wouldn't be any exported symbols at all. But when symbols are explicitly exported via DEF files, or implicitly exported via function attributes, the default flips to not exporting anything else β unless you give this option. Periodt.
And now the β¨do-not-pass-go listβ¨ β these will not be automatically exported:
DllMain@12DllEntryPoint@0DllMainCRTStartup@12impure_ptr
Also, symbols imported from other DLLs won't be re-exported, and neither will symbols specifying the DLL's internal layout β like the ones beginning with _head_ or ending with _iname. π
In addition, no symbols from libgcc, libstd++, libmingw32, or crtX.o will be exported. And symbols whose names begin with __rtti_ or __builtin_ won't be exported either β that one's to help with C++ DLLs. π§
Finally, there's a whole extensive list of cygwin-private symbols that are not exported (obviously, this applies when building DLLs for cygwin targets). The cygwin-excludes are:
_cygwin_dll_entry@12_cygwin_crt0_common@8_cygwin_noncygwin_dll_entry@12_fmode_impure_ptrcygwin_attach_dllcygwin_premain0cygwin_premain1cygwin_premain2cygwin_premain3environ
[This option is specific to the i386 PE targeted port of the linker]
--exclude-symbols symbol,symbol,...β hands you the aux cord: this 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β says the quiet part out loud: no symbols should be automatically exported. [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. This defaults to512. πΈ [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. The default is1MBreserved,4Kcommitted. π«Ά [This option is specific to the i386 PE targeted port of the linker]--image-base valueβ usevalueas 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. The default is0x400000for executables, and0x10000000for 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 are exported. βοΈ [This option is specific to the i386 PE targeted port of the linker]--large-address-awareβ if given, the appropriate bit in theCharacteristicsfield 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/3GBor/USERVA=valuemegabytes 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-awareoption. This is useful if--large-address-awareis 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 theimage version. Defaults to1. [This option is specific to the i386 PE targeted port of the linker]--major-os-version valueβ sets the major number of theos version. Defaults to4. [This option is specific to the i386 PE targeted port of the linker]--major-subsystem-version valueβ sets the major number of thesubsystem version. Defaults to4. [This option is specific to the i386 PE targeted port of the linker]--minor-image-version valueβ sets the minor number of theimage version. Defaults to0. [This option is specific to the i386 PE targeted port of the linker]--minor-os-version valueβ sets the minor number of theos version. Defaults to0. [This option is specific to the i386 PE targeted port of the linker]--minor-subsystem-version valueβ sets the minor number of thesubsystem version. Defaults to0. [This option is specific to the i386 PE targeted port of the linker]--output-def fileβ the linker will create the filefilewhich 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 withdlltool, 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 basevalue, unless one is specified using the--image-baseargument. 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 is 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>.dllin preference tolib<basename>.dll. This behaviour allows easy distinction between DLLs built for the varioussubplatforms: 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β does the β¨sophisticatedβ¨ linking of_symbolto__imp__symbolfor DATA imports from DLLs, thus making it possible to bypass the dllimport mechanism on the user side and to reference unmangled symbol names. π [This option is specific to the i386 PE targeted port of the linker]
The following remarks pertain to the original implementation of the feature and are obsolete nowadays for Cygwin and MinGW targets.
Note: use of the auto-import extension will cause the text section of the image file to be made writable. This does not conform to the PE-COFF format specification published by Microsoft. π
Note β use of the auto-import extension will also cause read only data which would normally be placed into the .rdata section to be placed into the .data section instead. This is in order to work around a problem with consts that is described 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]);
}
okay so a fourth way to dodge this whole mess is to re-code your library to use a functional interface instead of a data interface for the offending variables β think set_foo() and get_foo() accessor functions. periodt. π
--disable-auto-importβ do not attempt to do sophisticated linking of"_symbol"to"__imp__symbol"for DATA imports from DLLs. (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-importsection β that is, DATA imports from a DLL with non-zero offset β this switch will create a vector of 'runtime pseudo relocations' which can be used by the 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. (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. (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 to0x1000. (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 is2MBreserved,4Kcommitted. (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). This option also implies--dynamicbaseand--enable-reloc-section.--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. This option also implies--enable-reloc-section.--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-timestampcan be used to insert a zero value for the timestamp, this ensuring that binaries produced from identical sources will compare identically.--enable-reloc-sectionβ create the base relocation table, which is necessary if the image is loaded at a different image base than specified in the PE header.
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 with64entries.--dsbt-index indexβ this option sets the DSBT index of the current executable or shared library to index. The default is0, which is appropriate for generating executables. If a shared library is generated with a DSBT index of0, 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.
--branch-stubβ this option enables linker branch relaxation by inserting branch stub sections when needed to extend the range of branches. This option is usually not required since C-SKY supports branch and call instructions that can access the full memory range and branch relaxation is normally handled by the compiler or assembler.--stub-group-size=Nβ this option allows finer control of linker branch stub creation. It sets the maximum size of a group of input sections that can be handled by one stub section. A negative value of N locates stub sections after their branches, while a positive value allows stub sections to appear either before or after the branches. Values of1or-1indicate that the linker should choose suitable defaults.
The 68HC11 and 68HC12 linkers support specific options to control the memory bank switching mapping and trampoline code generation.
--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 ofsingle,negative,multigotortarget. For more information refer to the Info entry forld.
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 options control the choice of microMIPS instructions used in code generated by the linker, such as that in the PLT or lazy binding stubs, or in relaxation. If--insn32is used, then the linker only uses 32-bit instruction encodings. By default or if--no-insn32is used, all instruction encodings are used, including 16-bit ones where possible.--ignore-branch-isa,--no-ignore-branch-isaβ these options control branch relocation checks for invalid ISA mode transitions. If--ignore-branch-isais 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-isais used a check is made causing the loss of an ISA mode transition to produce an error.--compact-branches,--no-compact-branchesβ these options control the generation of compact instructions by the linker in the PLT entries for MIPS R6.
For the pdp11-aout target, three variants of the output format can be produced as selected by the following options. The default variant for pdp11-aout is the --omagic option, whereas for other targets --nmagic is the default. The --imagic option is defined only for the pdp11-aout target, while the others are described here as they apply to the pdp11-aout target.
-N,--omagicβ mark the output as"OMAGIC"(0407) in the a.out header to indicate that the text segment is not to be write-protected and shared. Since the text and data sections are both readable and writable, the data section is allocated immediately contiguous after the text segment. This is the oldest format for PDP11 executable programs and is the default forldon PDP11 Unix systems from the beginning through2.11BSD.-n,--nmagicβ mark the output as"NMAGIC"(0410) in the a.out header to indicate that when the output file is executed, the text portion will be read-only and shareable among all processes executing the same file. This involves moving the data areas up to the first possible8Kbyte page boundary following the end of the text. This option creates a pure executable format.-z,--imagicβ okay so this one stamps your output as "IMAGIC" with the magic number0411in thea.outheader, which is basically a lil note that says "hey, when u run me, load the program text and data into separate address spaces" π«Ά it does that using the split instruction and data space feature of the memory management unit on the bigger PDP11 models. The way this doubles the address space available to your program?? iconic. The text segment is again pure, write-protected, and shareable, just like before. The only difference in the output format between this option and the others β besides the magic number β is that both the text and data sections start at location0. The-zoption selected this format back in 2.11BSD. Heads up bestie: this option creates a separate executable format. π--no-omagicβ equivalent to--nmagicforpdp11-aout. That's it, that's the whole vibe. β¨
πΈ ENVIRONMENT πΈ
You can change how ld behaves with the environment variables "GNUTARGET", "LDEMULATION" and "COLLECT_NO_DEMANGLE". Three lil knobs, three lil moods. π
"GNUTARGET" decides 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's 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 β and this is the part that saves us β the configuration procedure for BFD on each system places the conventional format for that system first in the search-list, so ambiguities get resolved in favor of convention. No cap. π¦
"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. So like... it depends, yk? π
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. So the env var sets the vibe, and the flags can override the vibe. Main character energy fr. π
π SEE ALSO π
ar(1), nm(1), objcopy(1), objdump(1), readelf(1) and the Info entries for binutils and ld.
Go read those too, bestie, they're all part of the friend group. π
β COPYRIGHT β
Copyright (c) 1991-2020 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 page, bestie!! you read all twelve parts, you absolute legend π no notes, ate and left zero crumbs π
this was binutils-2.35.1 from 2020-09-19, and yes she's serving LD(1) realness one last time β¨ππ
π¦ where this page comes from
- debian bookworm: binutils-djgpp 2.35.1+dfsg-2 Β· GPL-3.0-or-later
- ubuntu jammy: binutils-djgpp 2.35.1+dfsg-1 Β· GPL-3.0-or-later
- ubuntu noble: binutils-djgpp 2.35.1+dfsg-2 Β· GPL-3.0-or-later
- ubuntu resolute: binutils-djgpp 2.35.1+dfsg-2 Β· GPL-3.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms