LD(1)
๐
LD(1) โ the GNU linker, straight from GNU Development Tools โจ
๐ NAME ๐
ld โ the GNU linker. That's the whole name tag, bestie. ๐
โจ SYNOPSIS โจ
ld [options] objfile ...
๐ฆ DESCRIPTION ๐ฆ
Okay so ld combines a number of object and archive files, relocates their data, and ties up symbol references. Usually the last step in compiling a program is to run ld. Like the final boss of build steps. ๐
ld accepts Linker Command Language files written in a superset of AT&T's Link Editor Command Language syntax, to provide explicit and total control over the linking process. Total control. Main character energy. ๐
This man page does not describe the command language; see the ld entry in info for full details on the command language and on other aspects of the GNU linker. iykyk, the full lore lives in info. ๐ซถ
This version of ld uses the general purpose BFD libraries to operate on object files. This allows ld to read, combine, and write object files in many different formats---for example, COFF or a.out. Different formats may be linked together to produce any available kind of object file. Versatile icon behavior. ๐
Aside from its flexibility, the GNU linker is more helpful than other linkers in providing diagnostic information. Many linkers abandon execution immediately upon encountering an error; whenever possible, ld continues executing, allowing you to identify other errors (or, in some cases, to get an output file in spite of the error). Not it being the emotionally mature linker that keeps going. ๐ญ๐
The GNU linker ld is meant to cover a broad range of situations, and to be as compatible as possible with other linkers. As a result, you have many choices to control its behavior. Choices, choices, choices. Periodt. ๐
๐ OPTIONS ๐
The linker supports a plethora of command-line options, but in actual practice few of them are used in any particular context. For instance, a frequent use of ld is to link standard Unix object files on a standard, supported Unix system. On such a system, to link a file hello.o:
ld -o <output> /lib/crt0.o hello.o -lc
This tells ld to produce a file called output as the result of linking the file /lib/crt0.o with hello.o and the library libc.a, which will come from the standard search directories. (See the discussion of the -l option below.) Slay. ๐
Some of the command-line options to ld may be specified at any point in the command line. However, options which refer to files, such as -l or -T, cause the file to be read at the point at which the option appears in the command line, relative to the object files and other file options. Repeating non-file options with a different argument will either have no further effect, or override prior occurrences (those further to the left on the command line) of that option. Options which may be meaningfully specified more than once are noted in the descriptions below. So yes, order matters sometimes. Noted. ๐
Non-option arguments are object files or archives which are to be linked together. They may follow, precede, or be mixed in with command-line options, except that an object file argument may not be placed between an option and its argument. Keep that boundary, bestie. ๐ง
Usually the linker is invoked with at least one object file, but you can specify other forms of binary input files using -l, -R, and the script command language. If no binary input files at all are specified, the linker does not produce any output, and issues the message No input files. Lowkey iconic error message. ๐
If the linker cannot recognize the format of an object file, it will assume that it is a linker script. A script specified in this way augments the main linker script used for the link (either the default linker script or the one specified by using -T). This feature permits the linker to link against a file which appears to be an object or an archive, but actually merely defines some symbol values, or uses INPUT or GROUP to load other objects. Specifying a script in this way merely augments the main linker script, with the extra commands placed after the main script; use the -T option to replace the default linker script entirely, but note the effect of the INSERT command. Plot twist: that object file might be a script in disguise. ๐ง
For options whose names are a single letter, option arguments must either follow the option letter without intervening whitespace, or be given as separate arguments immediately following the option that requires them. Single-letter options are clingy like that. ๐ซถ
For options whose names are multiple letters, either one dash or two can precede the option name; for example, -trace-symbol and --trace-symbol are equivalent. Note---there is one exception to this rule. Multiple letter options that start with a lower case 'o' can only be preceded by two dashes. This is to reduce confusion with the -o option. So for example -omagic sets the output file name to magic whereas --omagic sets the NMAGIC flag on the output. The more you know. โญ
Arguments to multiple-letter options must either be separated from the option name by an equals sign, or be given as separate arguments immediately following the option that requires them. For example --trace-symbol foo and --trace-symbol=foo are equivalent. Unique abbreviations of the names of multiple-letter options are accepted. Abbreviations? Accepted. We love a flexible queen. ๐
Note---if the linker is being invoked indirectly, via a compiler driver (e.g. gcc) then all the linker command line options should be prefixed by -Wl, (or whatever is appropriate for the particular compiler driver) like this:
gcc -Wl,--start-group foo.o bar.o -Wl,--end-group
This is important, because otherwise the compiler driver program may silently drop the linker options, resulting in a bad link. Confusion may also arise when passing options that require values through a driver, as the use of a space between option and argument acts as a separator, and causes the driver to pass only the option to the linker and the argument to the compiler. In this case, it is simplest to use the joined forms of both single- and multiple-letter options, such as:
gcc foo.o bar.o -Wl,-eENTRY -Wl,-Map=a.map
๐จ Bestie, do not let the compiler driver silently drop your linker options. That's a bad-link jump scare. Use -Wl, and the joined forms. No cap.
Here is a table of the generic command line switches accepted by the GNU linker (but make it a bullet list, because terminal tables are not the vibe, and every switch still gets its moment โจ):
@fileโ Read command-line options fromfile. The options read are inserted in place of the original@fileoption. Iffiledoes not exist, or cannot be read, then the option will be treated literally, and not removed. Options infileare 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@fileoptions; any such options will be processed recursively. Recursive? She contains multitudes. ๐-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. HP/UX said "hey can you..." andldsaid "say less." ๐--auditAUDITLIB โ Adds AUDITLIB to theDT_AUDITentry of the dynamic section. AUDITLIB is not checked for existence, nor will it use theDT_SONAMEspecified 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 thertld-auditinterface. ELF girlies, this one's for you. ๐ง-Aarchitecture,--architecture=architectureโ In the current release ofld, this option is useful only for the Intel 960 family of architectures. In thatldconfiguration, the architecture argument identifies the particular architecture in the 960 family, enabling some safeguards and modifying the archive-library search path. Future releases ofldmay support similar functionality for other architecture families. Intel 960 family, this is your moment. โญ-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-bto switch formats explicitly (when linking object files of different formats), by including-binput-format before each group of object files in a particular format. The default format is taken from the environment variableGNUTARGET. You can also define the input format from a script, using the commandTARGET; Format-switching? We love a chameleon era. ๐ฆ-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 GNUlddocumentation. Introduce MRI script files with the option-c; use the-Toption to run linker scripts written in the general-purposeldscripting language. IfMRI-cmdfiledoes not exist,ldlooks for it in the directories specified by any-Loptions. MRI said "can we make it compatible?" andldsaid "bet." ๐-d,-dc,-dpโ These three options are equivalent; multiple forms are supported for compatibility with other linkers. They assign space to common symbols even if a relocatable output file is specified (with-r). The script commandFORCE_COMMON_ALLOCATIONhas the same effect. Three names, one vibe. ๐--depauditAUDITLIB,-PAUDITLIB โ Adds AUDITLIB to theDT_DEPAUDITentry of the dynamic section. AUDITLIB is not checked for existence, nor will it use theDT_SONAMEspecified 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 thertld-auditinterface. The-Poption is provided for Solaris compatibility. Solaris compatibility? We love an accommodating icon. ๐-eentry,--entry=entryโ Use entry as the explicit symbol for beginning execution of your program, rather than the default entry point. If there is no symbol named entry, the linker will try to parse entry as a number, and use that as the entry address (the number will be interpreted in base 10; you may use a leading0xfor base 16, or a leading0for base 8). Entry point? She's the main character. ๐--exclude-libs lib,lib,...โ okay so this one is a "don't auto-export from these archives" list ๐ you give it a list of archive libraries whose symbols should not get automatically exported, and the lib names can be separated by commas or colons, your choice bestie. If you say--exclude-libs ALLthen literally every symbol in every archive library gets excluded from automatic export, periodt. Heads up though: this option is only available for thei386 PEtargeted port of the linker and for ELF targeted ports. Fori386 PE, symbols that you explicitly listed in a.deffile still get exported no matter what this option says. For ELF targeted ports, the symbols affected by this option get treated as hidden.--exclude-modules-for-implib module,module,...โ this is the "don't auto-export but DO copy the whole thing into the import library" vibe ๐ซถ you give it a list of object files or archive members whose symbols shouldn't be automatically exported, but which should be copied wholesale into the import library that's being generated during the link. The module names can be delimited by commas or colons, and they have to match exactly the filenames thatldused to open the files โ for archive members that's just the member name, but for object files the name you list must include and precisely match any path used to specify the input file on the linker's command line (yes, literally character-for-character, no cap ๐). Again: only for thei386 PEtargeted port. And symbols explicitly listed in a.deffile are still exported regardless of this option.-E,--export-dynamic,--no-export-dynamicโ the main character of dynamic symbol tables โจ when you're creating a dynamically linked executable, using-Eor--export-dynamicmakes the linker add all symbols to the dynamic symbol table. And what's the dynamic symbol table? It's the set of symbols that are visible from dynamic objects at run time, iykyk.
If you don't use either of these options (or if you use --no-export-dynamic to restore the default behavior), the dynamic symbol table will normally contain only those symbols that are referenced by some dynamic object mentioned in the link.
Now here's the situation where you'd actually care: if you use "dlopen" to load a dynamic object that needs to refer back to the symbols defined by the program โ rather than some other dynamic object โ then you'll probably need this option when linking the program itself. ๐
You can also use the dynamic list to control which symbols get added to the dynamic symbol table, if the output format supports it โ see the description of --dynamic-list.
Note that this option is specific to ELF targeted ports. PE targets support a similar function to export all symbols from a DLL or EXE; see the description of --export-all-symbols below. ๐
-EBโ link big-endian objects. This affects the default output format. Big endian energy fr fr ๐-ELโ link little-endian objects. This affects the default output format. Little endian girlies rise ๐ธ-f name,--auxiliary=nameโ when you're creating an ELF shared object, this sets the internalDT_AUXILIARYfield to the specified name. What that does: it tells the dynamic linker that the symbol table of the shared object should be used as an auxiliary filter on the symbol table of the shared object name. ๐ซ
So if you later link a program against this filter object, then when you run the program, the dynamic linker will see the DT_AUXILIARY field. If the dynamic linker resolves any symbols from the filter object, it will first check whether there's a definition in the shared object name. If there is one, it'll be used instead of the definition in the filter object. Fun fact: the shared object name doesn't even need to exist ๐ซง which means the shared object name can be used to provide an alternative implementation of certain functions โ maybe for debugging, maybe for machine specific performance.
This option may be specified more than once, and the DT_AUXILIARY entries get created in the order in which they appear on the command line. Order matters bestie ๐
-F name,--filter=nameโ same vibe, different field ๐ when creating an ELF shared object, this sets the internalDT_FILTERfield to the specified name. This tells the dynamic linker that the symbol table of the shared object being created should be used as a filter on the symbol table of the shared object name.
If you later link a program against this filter object, then when you run the program, the dynamic linker will see the DT_FILTER field. The dynamic linker will resolve symbols according to the symbol table of the filter object as usual, but it will actually link to the definitions found in the shared object name. So the filter object can be used to select a subset of the symbols provided by the object name. Chef's kiss selection ๐
Some older linkers used the-Foption throughout a compilation toolchain for specifying object-file format for both input and output object files. The GNU linker uses other mechanisms for this purpose: the-b,--format,--oformatoptions, the"TARGET"command in linker scripts, and the"GNUTARGET"environment variable. The GNU linker will ignore the-Foption when not creating an ELF shared object. (so likeโฆ don't come for GNU ld with your ancient toolchain habits ๐)
-fini=nameโ when creating an ELF executable or shared object, call NAME when the executable or shared object is unloaded, by settingDT_FINIto the address of the function. By default, the linker uses_finias the function to call. Goodbye function, iconic ๐ฆ-gโ ignored. Provided for compatibility with other tools. That's it, that's the whole personality. ๐-G value,--gpsize=valueโ sets the maximum size of objects to be optimized using the GP register to size. This is only meaningful for object file formats such as MIPS ELF that support putting large and small objects into different sections. It's ignored for other object file formats. GP register bestie only ๐ง-h name,-soname=nameโ when creating an ELF shared object, set the internalDT_SONAMEfield to the specified name. Then, when an executable is linked with a shared object that has aDT_SONAMEfield, then when the executable is run the dynamic linker will attempt to load the shared object specified by theDT_SONAMEfield rather than using the file name given to the linker. Sneaky little rename, love that for us ๐-iโ perform an incremental link (same as option-r). Short and sweet ๐-init=nameโ when creating an ELF executable or shared object, call NAME when the executable or shared object is loaded, by settingDT_INITto the address of the function. By default, the linker uses_initas the function to call. The hello function, the opener, the main character โจ-l namespec,--library=namespecโ add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times (spam it, queen ๐ซถ). If namespec is of the form:filename,ldwill search the library path for a file calledfilename, otherwise it will search the library path for a file calledlibnamespec.a.
On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a .so extension indicates a shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename. No exceptions, periodt ๐
The linker will search an archive only once, at the location where it's specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again. Positional trauma fr ๐ญ
See the -( option for a way to force the linker to search archives multiple times.
You may list the same archive multiple times on the command line. (Iconic, go off ๐)
This type of archive searching is standard for Unix linkers. However โ heads up โ if you're using ld on AIX, note that it's different from the behaviour of the AIX linker.
-L searchdir,--library-path=searchdirโ add path searchdir to the list of paths thatldwill search for archive libraries andldcontrol scripts. You may use this option any number of times. The directories are searched in the order in which they're specified on the command line, and directories specified on the command line are searched before the default directories. All-Loptions apply to all-loptions, regardless of the order in which the options appear (yes, even if you write them in a chaotic order, they all see each other ๐).-Loptions do not affect howldsearches for a linker script unless the-Toption is specified.
If searchdir begins with "=" or $SYSROOT, then this prefix will be replaced by the sysroot prefix, controlled by the --sysroot option, or specified when the linker is configured. ๐
The default set of paths searched (without being specified with -L) depends on which emulation mode ld is using, and in some cases also on how it was configured.
The paths can also be specified in a link script with the "SEARCH_DIR" command. Directories specified this way are searched at the point in which the linker script appears in the command line. Timing is everything babes โฐ
-m emulationโ emulate the emulation linker. You can list the available emulations with the--verboseor-Voptions. ๐ต๏ธโโ๏ธ
If the -m option isn't used, the emulation is taken from the "LDEMULATION" environment variable, if that's defined.
Otherwise, the default emulation depends upon how the linker was configured. Mystery default, love that for us ๐
-M,--print-mapโ print a link map to the standard output. A link map provides information about the link, including the following:- Where object files are mapped into memory. ๐บ๏ธ
- How common symbols are allocated.
- All archive members included in the link, with a mention of the symbol which caused the archive member to be brought in.
- The values assigned to symbols.
Note โ symbols whose values are computed by an expression which involves a reference to a previous value of the same symbol may not have correct result displayed in the link map. This is because the linker discards intermediate results and only retains the final value of an expression. Under such circumstances the linker will display the final value enclosed by square brackets. Thus for example a linker script containing:
foo = 1
foo = foo * 4
foo = foo + 8
will produce the following output in the link map if the -M option is used:
0x00000001 foo = 0x1
[0x0000000c] foo = (foo * 0x4)
[0x0000000c] foo = (foo + 0x8)
See the brackets? That's the linker being like "this is the final answer bestie, I threw away my notes" ๐ญ๐
See Expressions for more information about expressions in linker scripts. ๐ (yes that was the tail of the last one, we move ๐ซถ)
-n,--nmagicโ this one turns off page alignment of sections, and it also disables linking against shared libraries. And if your output format supports Unix style magic numbers, it marks the output as"NMAGIC". ๐-N,--omagicโ sets the text and data sections to be readable and writable ๐ณ. Also, no page-aligning of the data segment, and linking against shared libraries gets disabled too. If the output format supports Unix style magic numbers, the output gets marked"OMAGIC".
Heads up bestie: even though a writable text section is allowed for PE-COFF targets, it does not conform to the format specification published by Microsoft. So likeโฆ it works, but it's lowkey not it. ๐
--no-omagicโ negates most of what-Ndid. It sets the text section to read-only and forces the data segment to be page-aligned. โจ
But note โ this option does not enable linking against shared libraries. For that you want -Bdynamic. Don't forget, iykyk.
-ooutput,--output=output โ uses output as the name for the programldproduces ๐ซถ. If you don't specify it,a.outis the default name. The script command"OUTPUT"can also specify the output file name.-Olevel โ if level is a numeric value greater than zero,ldoptimizes the output ๐ฅ. That might take significantly longer, so honestly? Only turn it on for the final binary. At the moment this option only affects ELF shared library generation, and future releases of the linker may make more use of it. Also rn there's no difference in the linker's behaviour between different non-zero values of this option โ but again, that may change with future releases. โญ-pluginname โ brings a plugin into the linking process. The name parameter is the absolute filename of the plugin. Usually the compiler adds this automatically when using link time optimization, but users can absolutely add their own plugins if they so wish ๐ .
Important tea: the location of the compiler originated plugins is different from the place where thear,nmandranlibprograms search for their plugins. For those commands to use a compiler based plugin it must first be copied into the${libdir}/bfd-pluginsdirectory. All gcc based linker plugins are backward compatible, so just copying in the newest one is sufficient. ๐ง
--push-stateโ lets you preserve the current state of the flags that govern input file handling, so they can all be restored with one corresponding--pop-stateoption โจ. The options covered are:-Bdynamic,-Bstatic,-dn,-dy,-call_shared,-non_shared,-static,-N,-n,--whole-archive,--no-whole-archive,-r,-Ur,--copy-dt-needed-entries,--no-copy-dt-needed-entries,--as-needed,--no-as-needed, and-a. One target for this option is specifications forpkg-config. When used with the--libsoption, all possibly needed libraries get listed and then possibly linked with all the time. It's better to return something like this:
-Wl,--push-state,--as-needed -libone -libtwo -Wl,--pop-state
--pop-stateโ undoes the effect of--push-state, restoring the previous values of the flags governing input file handling. ๐ฆ-q,--emit-relocsโ leaves relocation sections and their contents in fully linked executables. Post link analysis and optimization tools may need this info to perform correct modifications of executables ๐. The tradeoff? Bigger executables. ๐ This option is currently only supported on ELF platforms.--force-dynamicโ forces the output file to have dynamic sections. This one is specific to VxWorks targets. ๐ธ-r,--relocatableโ generates relocatable output, i.e. generates an output file that can in turn serve as input 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 you don't specify this option, an absolute file is produced. When linking C++ programs, this option will not resolve references to constructors โ for that, use-Ur. When an input file doesn't have the same format as the output file, partial linking is only supported if that input file contains no relocations. Different output formats can have further restrictions; for example, some"a.out"-based formats don't support partial linking with input files in other formats at all. ๐ This option does the same thing as-i.-Rfilename,--just-symbols=filename โ reads symbol names and their addresses from filename, but doesn't relocate it or include it in the output. This lets your output file refer symbolically to absolute locations of memory defined in other programs ๐. You may use this option more than once.
For compatibility with other ELF linkers, if the-Roption is followed by a directory name rather than a file name, it gets treated as the-rpathoption. Sneaky but true.
-s,--strip-allโ omits all symbol information from the output file. bye symbols ๐-S,--strip-debugโ omits debugger symbol information (but not all symbols) from the output file. much chiller than-sngl.--strip-discarded,--no-strip-discardedโ omit (or don't omit) global symbols defined in discarded sections. Enabled by default. โญ-t,--traceโ prints the names of the input files asldprocesses them. Lil running commentary, we love to see it ๐-Tscriptfile,--script=scriptfile โ use scriptfile as the linker script. This script replacesld's default linker script (rather than adding to it), so commandfile must specify everything necessary to describe the output file ๐ญ. If scriptfile doesn't exist in the current directory,ldlooks 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 is similar to the--scriptoption except that processing of the script is delayed until after the rest of the command line has been processed โจ. That lets options placed after--default-scripton the command line affect the behaviour of the linker script, which can be super important when the linker command line can't be directly controlled by the user (eg because the command line is being constructed by another tool, such asgcc). ๐ซถ-usymbol,--undefined=symbol โ forces symbol to be entered in the output file as an undefined symbol. Doing this may, for example, trigger linking of additional modules from standard libraries ๐ฅ.-umay be repeated with different option arguments to enter additional undefined symbols. This option is equivalent to the"EXTERN"linker script command.
If you're using this to force additional modules into the link, and it's an error for the symbol to remain undefined, then use --require-defined instead. fr fr.
--require-defined=symbol โ requires that symbol is defined in the output file. Same as--undefinedexcept that if symbol isn't defined in the output file, the linker issues an error and exits ๐. Same effect can be achieved in a linker script by using"EXTERN","ASSERT"and"DEFINED"together. This option can be used multiple times to require additional symbols. ๐-Urโ for anything other than C++ programs, this option is equivalent to-r: it generates relocatable output, i.e. an output file that can in turn serve as input 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. Don't mix it up bestie ๐ญ
--orphan-handling=MODE โ controls how orphan sections are handled. An orphan section is one not specifically mentioned in a linker script ๐ MODE can have any of the following values:"place"โ orphan sections are placed into a suitable output section following the strategy described in Orphan Sections. The option--uniquealso affects how sections are placed."discard"โ all orphan sections are discarded, by placing them in the/DISCARD/section."warn"โ the linker places the orphan section as for"place"and also issues a warning."error"โ the linker exits with an error if any orphan section is found. The default if--orphan-handlingisn't given is"place". โจ
--unique[=SECTION]โ creates a separate output section for every input section matching SECTION, or โ if the optional wildcard SECTION argument is missing โ for every orphan input section ๐ธ. An orphan section is one not specifically mentioned in a linker script. You may use this option multiple times on the command line; it prevents the normal merging of input sections with the same name, overriding output section assignments in a linker script. iconic behaviour honestly.-v,--version,-Vโ display the version number forld. The-Voption also lists the supported emulations. โญ-x,--discard-allโ delete all local symbols. all of them. gone. ๐-X,--discard-localsโ delete all temporary local symbols. (These symbols start with system-specific local label prefixes, typically.Lfor ELF systems orLfor traditionala.outsystems.) ๐ฆ-ysymbol,--trace-symbol=symbol โ prints the name of each linked file in which symbol appears. This option may be given any number of times. On many systems it's necessary to prepend an underscore ๐ซถ This is so useful when you have an undefined symbol in your link but you have no idea where the reference is coming from. detective mode ๐-Ypath โ adds path to the default library search path. This option exists for Solaris compatibility. ๐-zkeyword โ the recognized keywords are:bndpltโ always generate BND prefix in PLT entries. Supported for Linux/x86_64. ๐
okay bestie, we're still deep in the -z keyword section and it's giving "encyclopedia but make it cute" ๐
here's the rest, no skips, no cap.
call-nop=prefix-addr,call-nop=suffix-nop,call-nop=prefix-byte,call-nop=suffix-byteโ these specify the1-byte "NOP"padding when you're transforming an indirect call to a locally defined function,foo, via its GOT slot. Supported fori386andx86_64.call-nop=prefix-addrgenerates0x67 call foo.call-nop=suffix-nopgeneratescall foo 0x90.call-nop=prefix-bytegeneratesbyte call foo.call-nop=suffix-bytegeneratescall foo byte.
combreloc,nocombrelocโ combine multiple dynamic relocation sections and sort them to improve dynamic symbol lookup caching. Do not do this ifnocombreloc.common,nocommonโ 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-weak,nodynamic-undefined-weakโ make undefined weak symbols dynamic when building a dynamic object, if they are referenced from a regular object file and not forced local by symbol visibility or versioning. Do not make them dynamic 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.globalauditโ this option is only meaningful when building a dynamic executable. It marks the executable as requiring global auditing by setting the"DF_1_GLOBAUDIT"bit in the"DT_FLAGS_1"dynamic tag. Global auditing requires that any auditing library defined via the--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 forLinux/i386andLinux/x86_64.ibtโ generateGNU_PROPERTY_X86_FEATURE_1_IBTin.note.gnu.propertysection to indicate compatibility with IBT. This also impliesibtplt. Supported forLinux/i386andLinux/x86_64.initfirstโ this option is only meaningful when building a shared object. It marks the object so that its runtime initialization will occur before the runtime initialization of any other objects brought into the process at the same time. Similarly the runtime finalization of the object will occur after the runtime finalization of any other objects.interposeโ specify that the dynamic loader should modify its symbol search order so that symbols in this shared library interpose all other shared libraries not so marked.lazyโ when generating an executable or shared library, mark it to tell the dynamic linker to defer function call resolution to the point when the function is called (lazy binding), rather than at load time. Lazy binding is the default.loadfltrโ specify that the object's filters be processed immediately at runtime.max-page-size=value โ set the maximum memory page size supported to value.muldefsโ allow multiple definitions.nocopyrelocโ disable linker generated.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 to"dlopen".nodumpโ specify that the object can not be dumped by"dldump".noexecstackโ marks the object as not requiring executable stack.noextern-protected-dataโ don't treat protected data symbols as external when building a shared library. This option overrides the linker backend default. It can be used to work around incorrect relocations against protected data symbols generated by compiler. Updates on protected data symbols by another module aren't visible to the resulting shared library. Supported fori386andx86-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 forx86_64.nowโ when generating an executable or shared library, mark it to tell the dynamic linker to resolve all symbols when the program is started, or when the shared library is loaded by dlopen, instead of deferring function call resolution to the point when the function is first called.originโ specify that the object requires$ORIGINhandling in paths.relro,norelroโ create an ELF"PT_GNU_RELRO"segment header in the object. This specifies a memory segment that should be made read-only after relocation, if supported. Specifyingcommon-page-sizesmaller than the system page size will render this protection ineffective. Don't create an ELF"PT_GNU_RELRO"segment ifnorelro.separate-code,noseparate-codeโ create separate code"PT_LOAD"segment header in the object. This specifies a memory segment that should contain only instructions and must be in wholly disjoint pages from any other data. Don't create separate code"PT_LOAD"segment ifnoseparate-codeis used.shstkโ generateGNU_PROPERTY_X86_FEATURE_1_SHSTKin.note.gnu.propertysection to indicate compatibility with Intel Shadow Stack. Supported forLinux/i386andLinux/x86_64.stack-size=value โ specify a stack size for an ELF"PT_GNU_STACK"segment. Specifying zero will override any default non-zero sized"PT_GNU_STACK"segment creation.text,notext,textoffโ report an error ifDT_TEXTRELis set, i.e., if the binary has dynamic relocations in read-only sections. Don't report an error ifnotextortextoff.undefsโ do not report unresolved symbol references from regular object files, either when creating an executable, or when creating a shared library. This option is the inverse of-z defs.
Other keywords are ignored for Solaris compatibility. iykyk ๐ซถ
-(archives-),--start-grouparchives--end-groupโ the archives should be a list of archive files. They may be either explicit file names, or-loptions.
The specified archives are searched repeatedly until no new undefined references are created. Normally, an archive is searched only once in the order that it is specified on the command line. If a symbol in that archive is needed to resolve an undefined symbol referred to by an object in an archive that appears later on the command line, the linker would not be able to resolve that reference. By grouping the archives, they all get searched repeatedly until all possible references are resolved.
Using this option has a significant performance cost. It is best to use it only when there are unavoidable circular references between two or more archives.
--accept-unknown-input-arch,--no-accept-unknown-input-archโ tells the linker to accept input files whose architecture cannot be recognised. The assumption is that the user knows what they are doing and deliberately wants to link in these unknown input files. This was the default behaviour of the linker, before release2.14. The default behaviour from release2.14onwards is to reject such input files, and so the--accept-unknown-input-archoption has been added to restore the old behaviour.--as-needed,--no-as-neededโ this option affects ELFDT_NEEDEDtags for dynamic libraries mentioned on the command line after the--as-neededoption. Normally the linker will add aDT_NEEDEDtag for each dynamic library mentioned on the command line, regardless of whether the library is actually needed or not.--as-neededcauses aDT_NEEDEDtag to only be emitted for a library that at that point in the link satisfies a non-weak undefined symbol reference from a regular object file or, if the library is not found in 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 do not affect whether the library is seen as needed. This is similar to the rules for extraction of object files from archives.--no-as-neededrestores the default behaviour.--add-needed,--no-add-neededโ these two options have been deprecated because of the similarity of their names to the--as-neededand--no-as-neededoptions. They have been replaced by--copy-dt-needed-entriesand--no-copy-dt-needed-entries.-assertkeyword โ this option is ignored for SunOS compatibility.-Bdynamic,-dy,-call_sharedโ link against dynamic libraries. This is only meaningful on platforms for which shared libraries are supported. This option is normally the default on such platforms. The different variants of this option are for compatibility with various systems. You may use this option multiple times on the command line: it affects library searching for-loptions which follow it. periodt ๐-Bgroupโ sets the"DF_1_GROUP"flag in the"DT_FLAGS_1"entry in the dynamic section, bestie. This makes the runtime linker handle lookups in this object and its dependencies only inside the group โ--unresolved-symbols=report-allis implied. Only meaningful on ELF platforms that support shared libraries. ๐-Bstatic,-dn,-non_shared,-staticโ do not link against shared libraries. This is only meaningful on platforms where shared libraries are supported. The different variants exist for compatibility with various systems. You can use this option multiple times on the command line: it affects library searching for-loptions that follow it. This also implies--unresolved-symbols=report-all. It can be used with-sharedโ doing so means a shared library is being created, but all of the library's external references must be resolved by pulling in entries from static libraries. ๐ซถ-Bsymbolicโ when creating a shared library, bind references to global symbols to the definition within the shared library, if any. Normally, a program linked against a shared library can override the definition inside the shared library. This option can also be used with the--export-dynamicoption, when creating a position independent executable, to bind references to global symbols to the definition within the executable. Only meaningful on ELF platforms that support shared libraries and position independent executables. โจ-Bsymbolic-functionsโ same vibe as-Bsymbolic, but for global function symbols: when creating a shared library, bind references to global function symbols to the definition within the shared library, if any. This can also be used with--export-dynamicwhen creating a position independent executable, to bind references to global function symbols to the definition within the executable. Only meaningful on ELF platforms that support shared libraries and position independent executables. ๐--dynamic-list=dynamic-list-fileโ tells the linker the name of a dynamic list file. This is typically used when creating shared libraries to specify a list of global symbols whose references shouldn't be bound to the definition within the shared library, or when creating dynamically linked executables to specify a list of symbols that should be added to the symbol table in the executable. Only meaningful on ELF platforms that support shared libraries. The format of the dynamic list is the same as the version node without scope and node name โ seeVERSIONfor more info. ๐ฆ--dynamic-list-dataโ include all global data symbols in the dynamic list. simple as that, no cap. ๐--dynamic-list-cpp-newโ provides the builtin dynamic list for C++operator newanddelete. It's mainly useful for building sharedlibstdc++. ๐--dynamic-list-cpp-typeinfoโ provides the builtin dynamic list for C++ runtime type identification. iykyk. ๐ธ--check-sections,--no-check-sectionsโ controls whether the linker checks section addresses after they've been assigned, looking for overlaps.--no-check-sectionsasks the linker not to check. Normally the linker does perform this check, and if it finds overlaps it produces suitable error messages. The linker does know about, and does make allowances for, sections in overlays. The default behaviour can be restored with--check-sections. Section overlap is not usually checked for relocatable links โ you can force checking in that case by using the--check-sectionsoption. ๐--copy-dt-needed-entries,--no-copy-dt-needed-entriesโ this pair affects how the linker treats dynamic libraries referred to byDT_NEEDEDtags inside ELF dynamic libraries mentioned on the command line. Normally the linker won't add aDT_NEEDEDtag to the output binary for each library mentioned in aDT_NEEDEDtag in an input dynamic library. With--copy-dt-needed-entriesspecified on the command line, however, any dynamic libraries that follow it will have theirDT_NEEDEDentries added. The default behaviour can be restored with--no-copy-dt-needed-entries.
This option also affects symbol resolution in dynamic libraries. With --copy-dt-needed-entries, dynamic libraries mentioned on the command line will be recursively searched โ following their DT_NEEDED tags to other libraries โ in order to resolve symbols required by the output binary. With the default setting, however, searching of dynamic libraries that follow it will stop with the dynamic library itself. No DT_NEEDED links will be traversed to resolve symbols. ๐ญ
--crefโ outputs a cross reference table. If a linker map file is being generated, the cross reference table is printed to the map file; otherwise it's printed on standard output. The format is intentionally simple so it can be easily processed by a script if necessary. Symbols are printed out sorted by name, and for each symbol a list of file names is given. If the symbol is defined, the first file listed is the location of the definition. If the symbol is defined as a common value, then any files where this happens appear next. Finally, any files that reference the symbol are listed. ๐ฅ--no-define-commonโ inhibits assigning addresses to common symbols. The script command"INHIBIT_COMMON_ALLOCATION"has the same effect. This option lets you decouple the decision to assign addresses toCommonsymbols from the choice of output file type; otherwise anon-Relocatableoutput type forces assigning addresses toCommonsymbols. Using--no-define-commonallowsCommonsymbols that are referenced from a shared library to be assigned addresses only in the main program. That eliminates the unused duplicate space in the shared library, and also prevents any possible confusion over resolving to the wrong duplicate when there are many dynamic modules with specialized search paths for runtime symbol resolution. ๐--force-group-allocationโ causes the linker to place section group members like normal input sections and to delete the section groups. This is the default behaviour for a final link, but this option can be used to change the behaviour of a relocatable link (-r). The script command"FORCE_GROUP_ALLOCATION"has the same effect. ๐--defsym=symbol=expressionโ creates a global symbol in the output file containing the absolute address given by expression. You may use this option as many times as necessary to define multiple symbols on the command line. A limited form of arithmetic is supported for expression in this context: you may give a hexadecimal constant or the name of an existing symbol, or use+and-to add or subtract hexadecimal constants or symbols. If you need more elaborate expressions, consider using the linker command language from a script. โ ๏ธ Note: there should be no white space between symbol, the equals sign ("="), and expression. ๐--demangle[=style],--no-demangleโ these control whether to demangle symbol names in error messages and other output. When told to demangle, the linker tries to present symbol names in a readable way: it strips leading underscores if the object file format uses them, and converts C++ mangled symbol names into user-readable names. Different compilers have different mangling styles, and the optional style argument can be used to pick an appropriate demangling style for your compiler. The linker demangles by default unless the environment variableCOLLECT_NO_DEMANGLEis set. These options may be used to override the default. ๐ง-Ifile,--dynamic-linker=fileโ sets the name of the dynamic linker. This is only meaningful when generating dynamically linked ELF executables.
โ ๏ธ The default dynamic linker is normally correct; don't use this unless you know what you are doing. ๐
--no-dynamic-linkerโ when producing an executable file, omit the request for a dynamic linker to be used at load-time. This is only meaningful for ELF executables that contain dynamic relocations, and usually requires entry point code capable of processing those relocations. ๐ฆ--embedded-relocsโ similar to the--emit-relocsoption, except the relocs are stored in a target specific section. This is only supported by theBFIN,CR16andM68Ktargets. ๐--fatal-warnings,--no-fatal-warningsโ treat all warnings as errors. The default behaviour can be restored with--no-fatal-warnings. ๐ค--force-exe-suffixโ makes sure an output file has a.exesuffix. If a successfully built fully linked output file does not have a".exe"or".dll"suffix, this forces the linker to copy the output file to one of the same name with a".exe"suffix. Useful when using unmodified Unix makefiles on a Microsoft Windows host, since some versions of Windows won't run an image unless it ends in a".exe"suffix. ๐ช--gc-sections,--no-gc-sectionsโ enables garbage collection of unused input sections. It's ignored on targets that don't support this option. The default behaviour โ not performing this garbage collection โ can be restored by specifying--no-gc-sectionson the command line. Note that garbage collection forCOFFandPEformat targets is supported, but the implementation is currently considered experimental. ๐
--gc-sections decides which input sections are used by examining symbols and relocations. The section containing the entry symbol and all sections containing symbols undefined on the command line will be kept, as will sections containing symbols referenced by dynamic objects. Note that when building shared libraries, the linker must assume that any visible symbol is referenced. Once this initial set of sections is determined, the linker recursively marks as used any section referenced by their relocations. See --entry and --undefined. ๐
This option can be set when doing a partial link, enabled with option -r. In that case, the root of symbols kept must be explicitly specified either by an --entry or --undefined option, or by an "ENTRY" command in the linker script. ๐
--print-gc-sections,--no-print-gc-sectionsโ okay so this one literally lists out every single section that got yeeted by garbage collection ๐๏ธโจ, and the whole list gets printed onstderr. But bestie listen โ it only does anything if you already turned on garbage collection with the--gc-sectionsoption, otherwise it's just standing there with nothing to report ๐. The default vibe (i.e. not listing the removed sections) can be brought right back by passing--no-print-gc-sectionson the command line. Slay ๐--gc-keep-exportedโ when--gc-sectionsis enabled, this one stops garbage collection from touching unused input sections that contain global symbols with default or protected visibility ๐. It's meant for executables where unreferenced sections would otherwise get collected no matter what the external visibility of the contained symbols is. Heads up though: it does nothing when you're linking shared objects, because that's already the default behaviour there ๐. And it's only supported for ELF format targets, periodt.--print-output-formatโ prints the name of the default output format (which, ngl, might have been influenced by other command-line options ๐). This is literally the string that would show up in anOUTPUT_FORMATlinker script command. Iconic.--print-memory-usageโ prints used size, total size and used size of the memory regions created with theMEMORYcommand ๐ง โจ. Super useful on embedded targets when you just want a quick lil view of how much free memory is left. The output format is one headline plus one line per region, and it's both human readable and easily parsable by tools โ best of both worlds honestly ๐ซถ. Here's what an example output looks like:
Memory region Used Size Region Size %age Used
ROM: 256 KB 1 MB 25.00%
RAM: 32 B 2 GB 0.00%
--helpโ prints a summary of the command-line options on the standard output and then dips โ๏ธ.--target-helpโ prints a summary of all the target specific options on the standard output and exits. Same energy, different guest list ๐ .-Map=mapfileโ prints a link map to the file mapfile. Peep the description of the-Moption, above, for the lore ๐.--no-keep-memoryโ soldnormally optimizes for speed over memory usage by caching the symbol tables of input files in memory ๐โโ๏ธ๐จ. This option tellsldto optimize for memory usage instead, by rereading the symbol tables whenever it needs them. You might lowkey need this ifldruns out of memory space while linking a huge executable ๐ญ.--no-undefined,-z defsโ reports unresolved symbol references from regular object files ๐. It does this even if the linker is creating a non-symbolic shared library. The switch--[no-]allow-shlib-undefinedcontrols the behaviour for reporting unresolved references found in shared libraries being linked in. And the effects of this option can be reverted by using-z undefs. Cool cool cool ๐ง--allow-multiple-definition,-z muldefsโ normally when a symbol is defined multiple times, the linker reports a fatal error ๐. These options allow multiple definitions, and the first definition will be the one used. First come, first served, no cap.--allow-shlib-undefined,--no-allow-shlib-undefinedโ allows or disallows undefined symbols in shared libraries. This switch is similar to--no-undefinedexcept it decides the behaviour when the undefined symbols are in a shared library rather than a regular object file ๐ฆ. It does not affect how undefined symbols in regular object files are handled.
The default behaviour is to report errors for any undefined symbols referenced in shared libraries if the linker is being used to create an executable, but to allow them if the linker is being used to create a shared library.
The reasons for allowing undefined symbol references in shared libraries specified at link time are that:
- A shared library specified at link time may not be the same as the one that is available at load time, so the symbol might actually be resolvable at load time ๐.
- There are some operating systems, eg BeOS and HPPA, where undefined symbols in shared libraries are normal.
The BeOS kernel for example patches shared libraries at load time to select whichever function is most appropriate for the current architecture. This is used, for example, to dynamically select an appropriate memset function. Kinda iconic of them tbh โจ
--no-undefined-versionโ normally when a symbol has an undefined version, the linker just ignores it ๐. This option disallows symbols with undefined version, and a fatal error gets issued instead. Glow-up with consequences ๐--default-symverโ creates and uses a default symbol version (the soname) for unversioned exported symbols.--default-imported-symverโ creates and uses a default symbol version (the soname) for unversioned imported symbols. Matching set, we love to see it ๐--no-warn-mismatchโ normallyldgives you an error if you try to link together input files that are mismatched for some reason, maybe because they were compiled for different processors or for different endiannesses ๐ฌ. This option tellsldto silently permit such possible errors. Use this with care only, in cases where you've taken some special action that ensures the linker errors are inappropriate. Like, don't just turn it on for funsies, bestie ๐--no-warn-search-mismatchโ normallyldgives a warning if it finds an incompatible library during a library search. This option silences that warning ๐คซ.--no-whole-archiveโ turns off the effect of the--whole-archiveoption for subsequent archive files. Undo button, but make it linker ๐ฎ--noinhibit-execโ retains the executable output file whenever it's still usable. Normally the linker won't produce an output file if it encounters errors during the link process โ it exits without writing an output file when it issues any error whatsoever ๐. This says "nah, keep it".-nostdlibโ only search library directories explicitly specified on the command line. Library directories specified in linker scripts (including linker scripts specified on the command line) are straight-up ignored ๐ โโ๏ธ.--oformat=output-formatโ soldmay be configured to support more than one kind of object file. If yourldis configured that way, you can use the--oformatoption to specify the binary format for the output object file โจ. Even whenldis configured to support alternative object formats, you don't usually need to specify this, sinceldshould be configured to produce as a default output format the most usual format on each machine. output-format is a text string โ the name of a particular format supported by the BFD libraries. (You can list the available binary formats withobjdump -i.) The script commandOUTPUT_FORMATcan also specify the output format, but this option overrides it ๐.--out-implib fileโ creates an import library in file corresponding to the executable the linker is generating (eg. a DLL or ELF program). This import library (which should be called*.dll.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). Only available for the i386 PE and ELF targetted ports of the linker, iykyk.-pie,--pic-executableโ creates a position independent executable ๐ฆ. Currently only supported on ELF platforms. Position independent executables are similar to shared libraries in that they're relocated by the dynamic linker to the virtual address the OS chooses for them (which can vary between invocations ๐). Like normal dynamically linked executables they can be executed, and symbols defined in the executable cannot be overridden by shared libraries.-qmagicโ this option is ignored for Linux compatibility. It's giving "we keep it around for the vibes" ๐-Qyโ this option is ignored for SVR4 compatibility. Same energy, different ancestor ๐--relax,--no-relaxโ an option with machine dependent effects, only supported on a few targets ๐ฏ.
On some platforms the --relax option performs target specific, global optimizations that become possible when the linker resolves addressing in the program, such as relaxing address modes, synthesizing new instructions, selecting shorter version of current instructions, and combining constant values. Little glow-ups everywhere โจ
On some platforms these link time global optimizations may make symbolic debugging of the resulting executable impossible ๐ญ. This is known to be the case for the Matsushita MN10200 and MN10300 family of processors.
On platforms where this is not supported, --relax is accepted, but ignored.
On platforms where --relax is accepted, the option --no-relax can be used to disable the feature. Off switch acquired ๐
--retain-symbols-file=filenameโ retains only the symbols listed in the file filename, discarding all others โ๏ธ. filename is simply a flat file, with one symbol name per line. This option is especially useful in environments (such as VxWorks) where a large global symbol table is accumulated gradually, to conserve run-time memory.
--retain-symbols-file does not discard undefined symbols, or symbols needed for relocations. Important detail, don't forget it ๐
You may only specify --retain-symbols-file once in the command line. It overrides -s and -S.
-rpath=dirโ adds a directory to the runtime library search path ๐ฃ๏ธ. This is used when linking an ELF executable with shared objects. All-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. If-rpathis not used when linking an ELF executable, the contents of the environment variableLD_RUN_PATHwill be used if it is defined ๐.
The -rpath option may also be used on SunOS. By default, on SunOS, the linker will form a runtime search path out of all the -L options it is given. If a -rpath option is used, the runtime search path will be formed exclusively using the -rpath options, ignoring the -L options ๐
โโ๏ธ. This can be useful when using gcc, which adds many -L options which may be on NFS mounted file systems.
For compatibility with other ELF linkers, if the -R option is followed by a directory name, rather than a file name, it is treated as the -rpath option. Sneaky but handy ๐ง
-rpath-link=dirโ when using ELF or SunOS, one shared library may require another. This happens when anld -sharedlink includes a shared library as one of the input files ๐ฆ.
...okay so when the linker runs into a dependency like this during a non-shared, non-relocatable link, it's gonna auto-try to find the shared library it needs and pull it into the link, assuming you didn't already include it explicitly. ๐ And that's where -rpath-link swoops in โ it gives the first set of directories to search. You can hand it a whole sequence of directory names, either by listing them separated by colons, or just by using the option multiple times. Slay, flexible queen. โจ
The tokens $ORIGIN and $LIB can show up in these search directories too, iykyk:
$ORIGINโ gets replaced by the full path to the directory holding the program or shared object$LIBโ gets replaced by eitherlib(for 32-bit binaries) orlib64(for 64-bit binaries)
The alternative form of these tokens โ ${ORIGIN} and ${LIB} โ also works. But the token $PLATFORM? not supported. ๐
โโ๏ธ
โ ๏ธ Use this option with caution, bestie โ it overrides the search path that may have been hard compiled into a shared library. Which means yeah, it's genuinely possible to unintentionally end up using a different search path than the runtime linker would've used. ๐ญ
So here's the whole rundown โ the linker uses these search paths, in this order, to locate required shared libraries:
- Any directories specified by
-rpath-linkoptions. - Any directories specified by
-rpathoptions. The difference between-rpathand-rpath-link? Directories from-rpathget included in the executable and used at runtime, whereas-rpath-linkis only effective at link time. Searching-rpaththis way is only supported by native linkers and cross linkers that were configured with the--with-sysrootoption. - On an ELF system, for native linkers, if
-rpathand-rpath-linkweren't used, it searches the contents of the environment variableLD_RUN_PATH. - On SunOS, if
-rpathwasn't used, it searches any directories specified using-Loptions. - For a native linker, it searches the contents of the environment variable
LD_LIBRARY_PATH. - For a native ELF linker, the directories in
DT_RUNPATHorDT_RPATHof a shared library get searched for shared libraries that it needs. TheDT_RPATHentries are ignored ifDT_RUNPATHentries exist. - The default directories โ normally
/liband/usr/lib. - For a native linker on an ELF system, if the file
/etc/ld.so.confexists, the list of directories found in that file.
And if the required shared library just... isn't found? The linker throws a warning and keeps going with the link. ๐
-shared,-Bshareableโ creates a shared library ๐. Currently only supported on ELF, XCOFF and SunOS platforms. On SunOS, the linker will automatically create a shared library if the-eoption isn't used and there are undefined symbols in the link.--sort-common,--sort-common=ascending,--sort-common=descendingโ tellsldto sort the common symbols by alignment in ascending or descending order when it places them in the appropriate output sections. The symbol alignments it considers are sixteen-byte or larger, eight-byte, four-byte, two-byte, and one-byte โ all so you don't get gaps between symbols from alignment constraints. No sorting order specified? Descending is assumed. ๐--sort-section=nameโ appliesSORT_BY_NAMEto all wildcard section patterns in the linker script.--sort-section=alignmentโ appliesSORT_BY_ALIGNMENTto all wildcard section patterns in the linker script.--spare-dynamic-tags=countโ specifies how many empty slots to leave in the.dynamicsection of ELF shared objects. Post processing tools like the prelinker might need those empty slots. Default is5. ๐ซถ--split-by-file[=size]โ similar to--split-by-reloc, but creates a new output section for each input file whensizeis reached.sizedefaults to1if you don't give it one.--split-by-reloc[=count]โ tries to create extra sections in the output file so that no single output section in the file contains more thancountrelocations. Super useful when generating huge relocatable files for downloading into certain real time kernels with the COFF object file format, since COFF literally cannot represent more than65535relocations in a single section. Heads up though: this will fail to work with object file formats that don't support arbitrary sections. Also the linker won't split up individual input sections for redistribution โ so if a single input section contains more thancountrelocations, one output section will contain that many relocations.countdefaults to32768.--statsโ computes and displays statistics about the linker's operation, like execution time and memory usage. ๐--sysroot=directoryโ uses directory as the location of the sysroot, overriding the configure-time default. Only supported by linkers that were configured using--with-sysroot.--task-linkโ used by COFF/PE based targets to create a task-linked object file where all the global symbols have been converted to statics.--traditional-formatโ for some targets, the output oflddiffers in some ways from the output of some existing linker, and this switch asksldto use the traditional format instead.
For example, on SunOS, ld combines duplicate entries in the symbol string table โ which can shrink an output file with full debugging information by over 30 percent. Unfortunately the SunOS dbx program can't read the resulting program (gdb has no trouble though ๐). The --traditional-format switch tells ld not to combine duplicate entries.
--section-start=sectionname=orgโ locates a section in the output file at the absolute address given by org. Use it as many times as you need to locate multiple sections on the command line. org must be a single hexadecimal integer, and for compatibility with other linkers you can omit the leading0xusually associated with hex values. Note: there should be no white space between sectionname, the equals sign (=), and org. ๐จ-Tbss=org,-Tdata=org,-Ttext=orgโ same as--section-start, with.bss,.dataor.textas the sectionname.-Ttext-segment=orgโ when creating an ELF executable, sets the address of the first byte of the text segment.-Trodata-segment=orgโ when creating an ELF executable or shared object for a target where the read-only data lives in its own segment separate from the executable text, sets the address of the first byte of the read-only data segment.-Tldata-segment=orgโ when creating an ELF executable or shared object for x86-64 medium memory model, sets the address of the first byte of the ldata segment.--unresolved-symbols=methodโ decides how unresolved symbols get handled. Four possible values for method:ignore-allโ don't report any unresolved symbols.report-allโ report all unresolved symbols. This is the default.ignore-in-object-filesโ report unresolved symbols contained in shared libraries, but ignore them if they come from regular object files.ignore-in-shared-libsโ report unresolved symbols that come from regular object files, but ignore them if they come from shared libraries. Handy when you're creating a dynamic binary and you know all the shared libraries it should be referencing are already on the linker's command line. ๐
The behaviour for shared libraries on their own can also be controlled by the --[no-]allow-shlib-undefined option.
Normally the linker generates an error message for each reported unresolved symbol, but --warn-unresolved-symbols can switch that to a warning instead.
--dll-verbose,--verbose[=NUMBER]โ displays the version number forldand lists the linker emulations supported. Also shows which input files can and cannot be opened, plus which linker script the linker is using. And if the optionalNUMBERargument is> 1, plugin symbol status gets displayed too. โจ--version-script=version-scriptfileโ names a version script for the linker. Typically used when creating shared libraries to specify extra info about the version hierarchy for the library being created. Only fully supported on ELF platforms that support shared libraries โ seeVERSION. It's partially supported on PE platforms, which can use version scripts to filter symbol visibility in auto-export mode: any symbols marked local in the version script won't be exported.--warn-commonโ warns when a common symbol gets combined with another common symbol or with a symbol definition. Unix linkers allow this kinda sloppy practice, but linkers on some other operating systems do not ๐. This option helps you find potential problems from combining global symbols. Unfortunately some C libraries use this practice, so you may get warnings about symbols in the libraries as well as in your programs.
There are three kinds of global symbols, illustrated here with C examples:
int i = 1;
A definition, which goes in the initialized data section of the output file.
extern int i;
An undefined reference, which doesn't allocate space. There must be either a definition or a common symbol for the variable somewhere.
int i;
A common symbol. If there are only (one or more) common symbols for a variable, it goes in the uninitialized data area of the output file. The linker merges multiple common symbols for the same variable into a single symbol, and if they're different sizes, it picks the largest size. And if there's a definition of the same variable, the linker turns a common symbol into a declaration. ๐
...and honestly bestie, --warn-common is a whole personality. It can produce five kinds of warnings, and each warning is a pair of lines: line one describes the symbol it just ran into, line two describes the previous symbol it saw with that same name. At least one of the two is always gonna be a common symbol. Let's break down all five like they're a text thread ๐ฑโจ
- Turning a common symbol into a reference, because there's already a definition for the symbol.
<file>(<section>): warning: common of `<symbol>'
overridden by definition
<file>(<section>): warning: defined here
- Turning a common symbol into a reference, because a later definition for the symbol shows up. Same situation as the previous one bestie, just the symbols arrived in a different order ๐
<file>(<section>): warning: definition of `<symbol>'
overriding common
<file>(<section>): warning: common is here
- Merging a common symbol with a previous common symbol of the same size ๐ค
<file>(<section>): warning: multiple common
of `<symbol>'
<file>(<section>): warning: previous common is here
- Merging a common symbol with a previous common symbol that's larger ๐
<file>(<section>): warning: common of `<symbol>'
overridden by larger common
<file>(<section>): warning: larger common is here
- Merging a common symbol with a previous common symbol that's smaller ๐ฅบ Same as the last one, except the symbols got encountered in a different order.
<file>(<section>): warning: common of `<symbol>'
overriding smaller common
<file>(<section>): warning: smaller common is here
--warn-constructorsโ yells at you if any global constructors are used. Lowkey only useful for a few object file formats โ for formats like COFF or ELF the linker literally can't detect global constructor use, so it's giving "can't even see it" energy ๐--warn-multiple-gpโ warns you when the output file needs more than one global pointer value. Only meaningful for certain processors, like the Alpha. The lore: some processors stash big-valued constants in a special section, and a special register (the global pointer) points into the middle of that section so constants load efficiently via base-register relative addressing. Since the offset in base-register relative mode is fixed and relatively small (like, 16 bits), that caps how big the constant pool can get ๐ฌ So in big programs you often need multiple global pointer values just to address all possible constants โ and this option warns whenever that case pops up.--warn-onceโ only warns once for each undefined symbol, instead of once per module that refers to it. Not me getting 40 identical warnings ๐ญ--warn-section-alignโ warns if an output section's address changes because of alignment. Usually the alignment gets set by an input section. The address only changes if it wasn't explicitly specified โ meaning theSECTIONScommand doesn't give that section a start address.--warn-shared-textrelโ warns if the linker adds aDT_TEXTRELto a shared object.--warn-alternate-emโ warns if an object has alternate ELF machine code.--warn-unresolved-symbolsโ if the linker is gonna report an unresolved symbol (see the--unresolved-symbolsoption), it normally generates an error. This option makes it generate a warning instead. Gentle parenting mode activated ๐ซถ--error-unresolved-symbolsโ restores the linker's default behaviour of generating errors when reporting unresolved symbols. Back to business fr.--whole-archiveโ for every archive mentioned on the command line after--whole-archive, include every object file in the archive in the link, instead of searching the archive for the object files it needs. Normally used to turn an archive file into a shared library, forcing every object into the resulting shared library. This option may be used more than once ๐
Two notes for when you're using this from gcc. First: gcc doesn't know about this option, so you gotta use -Wl,-whole-archive. Second: don't forget to use -Wl,-no-whole-archive after your list of archives, because gcc adds its own list of archives to your link and you probably don't want this flag affecting those too ๐
--wrap=symbol โ use a wrapper function for symbol. Any undefined reference to symbol resolves to__wrap_symbol. Any undefined reference to__real_symbolresolves to symbol.
This is how you provide a wrapper for a system function. The wrapper function should be called __wrap_symbol. If it wants to call the system function, it calls __real_symbol ๐
Here's a trivial example:
void *
__wrap_malloc (size_t c)
{
printf ("malloc called with %zu\n", c);
return __real_malloc (c);
}
If you link other code with this file using --wrap malloc, then all calls to malloc will call the function __wrap_malloc instead. The call to __real_malloc inside __wrap_malloc will call the real malloc function. Iconic behaviour honestly.
You may also wanna provide a __real_malloc function, so that links without the --wrap option still succeed. But if you do, do not put the definition of __real_malloc in the same file as __wrap_malloc โ if you do, the assembler may resolve the call before the linker even gets a chance to wrap it to malloc. Sneaky little race condition, no cap โ ๏ธ
--eh-frame-hdr,--no-eh-frame-hdrโ request (--eh-frame-hdr) or suppress (--no-eh-frame-hdr) the creation of the.eh_frame_hdrsection and the ELFPT_GNU_EH_FRAMEsegment header.--no-ld-generated-unwind-infoโ request creation of.eh_frameunwind info for linker-generated code sections like PLT. This option is on by default if linker-generated unwind info is supported.--enable-new-dtags,--disable-new-dtagsโ this linker can create the new dynamic tags in ELF, but older ELF systems may not understand them ๐ง If you specify--enable-new-dtags, the new dynamic tags get created as needed and older dynamic tags are omitted. If you specify--disable-new-dtags, no new dynamic tags are created. By default, the new dynamic tags are not created. Note that these options are only available for ELF systems.--hash-size=number โ sets the default size of the linker's hash tables to a prime number close to number. Bumping this up can reduce how long the linker takes to do its tasks, at the cost of more memory. Lowering it can reduce memory requirements, at the cost of speed. Pick your struggle bestie โ๏ธ--hash-style=style โ sets the type of the linker's hash table(s). style can besysvfor the classic ELF.hashsection,gnufor the new-style GNU.gnu.hashsection, orbothfor both the classic ELF.hashand the new-style GNU.gnu.hashhash tables. The default issysv.--compress-debug-sections=none,--compress-debug-sections=zlib,--compress-debug-sections=zlib-gnu,--compress-debug-sections=zlib-gabiโ on ELF platforms these control how DWARF debug sections get compressed with zlib ๐๏ธ
--compress-debug-sections=none doesn't compress DWARF debug sections. --compress-debug-sections=zlib-gnu compresses DWARF debug sections and renames them to start with .zdebug instead of .debug. --compress-debug-sections=zlib-gabi also compresses DWARF debug sections, but instead of renaming them it sets the SHF_COMPRESSED flag in the sections' headers.
The --compress-debug-sections=zlib option is an alias for --compress-debug-sections=zlib-gabi.
Note that this option overrides any compression in input debug sections โ so if a binary is linked with --compress-debug-sections=none, for example, then any compressed debug sections in input files get uncompressed before they're copied into the output binary.
The default compression behaviour varies depending on the target involved and the configure options used to build the toolchain. You can figure out the default by examining the output from the linker's --help option ๐
--reduce-memory-overheadsโ cuts memory requirements atldruntime, at the expense of linking speed. This was introduced to select the old O(n^2) algorithm for link map file generation, rather than the new O(n) algorithm which uses about 40% more memory for symbol storage.
Another effect of the switch: it sets the default hash table size to 1021, which again saves memory at the cost of lengthening the linker's run time. This is not done, however, if the --hash-size switch has been used.
The --reduce-memory-overheads switch may also be used to enable other tradeoffs in future versions of the linker. Foreshadowing โจ
--build-id,--build-id=style โ request the creation of a.note.gnu.build-idELF note section or a.buildidCOFF section. The contents of the note are unique bits identifying this linked file ๐ style can beuuidto use 128 random bits,sha1to use a 160-bit SHA1 hash on the normative parts of the output contents,md5to use a 128-bit MD5 hash on the normative parts of the output contents, or0xhexstringto use a chosen bit string specified as an even number of hexadecimal digits (-and:characters between digit pairs are ignored). If style is omitted,sha1is used.
The md5 and sha1 styles produce an identifier that's always the same in an identical output file, but will be unique among all nonidentical output files. It is not intended to be compared as a checksum for the file's contents ๐
โโ๏ธ A linked file may get changed later by other tools, but the build ID bit string identifying the original linked file doesn't change.
Passing none for style disables the setting from any --build-id options earlier on the command line.
okay bestie, so the i386 PE linker is out here supporting the -shared option โ which means the output becomes a dynamically linked library (DLL) instead of a normal executable. name your output *.dll when you use it, okay? ๐
and the tea is: the linker fully supports the standard *.def files too, and you can pass them on the linker command line just like an object file. (actually, it should come before the archives it exports symbols from, so they actually get linked in โ same energy as a normal object file, no cap.) ๐ซถ
on top of the options common to all targets, the i386 PE linker supports extra command line options specific to the i386 PE target. and options that take values? you can separate them from their values with either a space or an equals sign. easy. โจ
--add-stdcall-aliasโ if given, symbols with a stdcall suffix (@nn) get exported as-is and also with the suffix stripped. two for the price of one, iconic. [This option is specific to the i386 PE targeted port of the linker]--base-filefile โ use file as the name of a file where the base addresses of all the relocations needed for generating DLLs withdlltoolget saved. [This is an i386 PE specific option]--dllโ create a DLL instead of a regular executable. you can also use-sharedor specify aLIBRARYin a given.deffile, bestie. so many paths to the same slay. [This option is specific to the i386 PE targeted port of the linker]--enable-long-section-names,--disable-long-section-namesโ okay so the PE variants of the COFF object format add an extension that lets section names be longer than eight characters (which is the normal COFF limit). by default these names are only allowed in object files, because fully-linked executable images don't carry the COFF string table needed to support the longer names. but as a GNU extension you can allow their use in executable images too โ or (probably pointlessly!) disallow it in object files โ using these two options. heads up though: executable images generated with these long section names are slightly non-standard, literally carrying a string table, and may generate confusing output when examined with non-GNU PE-aware tools like file viewers and dumpers. ๐ญ however, GDB relies on PE long section names to find Dwarf-2 debug information sections in an executable image at runtime โ so if neither option is specified on the command line,ldwill enable long section names, overriding the default and technically correct behaviour, when it finds debug info present while linking an executable image and not stripping symbols. [This option is valid for all PE targeted ports of the linker]--enable-stdcall-fixup,--disable-stdcall-fixupโ if the link finds a symbol it can't resolve, it attempts "fuzzy linking" ๐ฎ by looking for another defined symbol that differs only in the format of the symbol name (cdecl vs stdcall) and resolves that symbol by linking to the match. example: the undefined symbol_foomight be linked to the function_foo@12, or the undefined symbol_bar@16might be linked to the function_bar. when the linker does this it prints a warning, since it normally should have failed to link โ but sometimes import libraries generated from third-party dlls need this feature to be usable. if you specify--enable-stdcall-fixup, this feature is fully enabled and warnings are not printed. if you specify--disable-stdcall-fixup, the feature is disabled and such mismatches are considered to be errors. [This option is specific to the i386 PE targeted port of the linker]--leading-underscore,--no-leading-underscoreโ for most targets the default symbol-prefix is an underscore, and it's defined in the target's description. with this option you can disable/enable the default underscore symbol-prefix. ๐ฆ--export-all-symbolsโ if given, all global symbols in the objects used to build a DLL get exported by the DLL. note that this is the default if there otherwise wouldn't be any exported symbols. when symbols are explicitly exported via DEF files or implicitly exported via function attributes, the default is to not export anything else unless this option is given. okay and now the big list of exceptions, buckle up ๐: the symbolsDllMain@12,DllEntryPoint@0,DllMainCRTStartup@12, andimpure_ptrwill not be automatically exported. also, symbols imported from other DLLs will not be re-exported, nor will symbols specifying the DLL's internal layout such as those beginning with_head_or ending with_iname. in addition, no symbols fromlibgcc,libstd++,libmingw32, orcrtX.owill be exported. symbols whose names begin with__rtti_or__builtin_will not be exported, to help with C++ DLLs. finally, there's an extensive list of cygwin-private symbols that are not exported (obviously this applies when building DLLs for cygwin targets). these cygwin-excludes are:_cygwin_dll_entry@12,_cygwin_crt0_common@8,_cygwin_noncygwin_dll_entry@12,_fmode,_impure_ptr,cygwin_attach_dll,cygwin_premain0,cygwin_premain1,cygwin_premain2,cygwin_premain3, andenviron. [This option is specific to the i386 PE targeted port of the linker]--exclude-symbolssymbol,symbol,... โ specifies a list of symbols which should not be automatically exported. the symbol names may be delimited by commas or colons. [This option is specific to the i386 PE targeted port of the linker]--exclude-all-symbolsโ specifies no symbols should be automatically exported. periodt, nothing gets out. ๐ซ [This option is specific to the i386 PE targeted port of the linker]--file-alignmentโ specify the file alignment. sections in the file will always begin at file offsets which are multiples of this number. defaults to512. [This option is specific to the i386 PE targeted port of the linker]--heapreserve,--heapreserve,commit โ specify the number of bytes of memory to reserve (and optionally commit) to be used as heap for this program. default is1MBreserved,4Kcommitted. [This option is specific to the i386 PE targeted port of the linker]--image-basevalue โ use value as the base address of your program or dll. this is the lowest memory location that will be used when your program or dll is loaded. to reduce the need to relocate and improve performance of your dlls, each should have a unique base address and not overlap any other dlls. default 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're exported. bye bye suffix โ๏ธ [This option is specific to the i386 PE targeted port of the linker]--large-address-awareโ if given, the appropriate bit in 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=valuemegabytesswitch 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-versionvalue โ sets the major number of the "image version". defaults to1. [This option is specific to the i386 PE targeted port of the linker]--major-os-versionvalue โ sets the major number of the "os version". defaults to4. [This option is specific to the i386 PE targeted port of the linker]--major-subsystem-versionvalue โ sets the major number of the "subsystem version". defaults to4. [This option is specific to the i386 PE targeted port of the linker]--minor-image-versionvalue โ sets the minor number of the "image version". defaults to0. [This option is specific to the i386 PE targeted port of the linker]--minor-os-versionvalue โ sets the minor number of the "os version". defaults to0. [This option is specific to the i386 PE targeted port of the linker]--minor-subsystem-versionvalue โ sets the minor number of the "subsystem version". defaults to0. [This option is specific to the i386 PE targeted port of the linker]--output-deffile โ the linker will create the file file, which will contain a DEF file corresponding to the DLL the linker is generating. this DEF file (which should be called*.def) may be used to create an import library withdlltoolor may be used as a reference to automatically or implicitly exported symbols. [This option is specific to the i386 PE targeted port of the linker]--enable-auto-image-base,--enable-auto-image-base=value โ automatically choose the image base for DLLs, optionally starting with base value, unless one is specified using the--image-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's no user-specified image base (--image-base) then use the platform default. [This option is specific to the i386 PE targeted port of the linker]--dll-search-prefixstring โ when linking dynamically to a dll without an import library, search for"<string><basename>.dll"in preference to"lib<basename>.dll". this behaviour allows easy distinction between DLLs built for the various "subplatforms": native, cygwin, uwin, pw, etc. for instance, cygwin DLLs typically use--dll-search-prefix=cyg. [This option is specific to the i386 PE targeted port of the linker]--enable-auto-importโ okay so this one does sophisticated linking of"_symbol"to"__imp__symbol"for DATA imports from DLLs, and it builds the necessary thunking symbols when you're making the import libraries with those DATA exports. ๐
โ ๏ธ Heads up bestie: using the 'auto-import' extension will cause the text section of the image file to be made writable. That does not conform to the PE-COFF format specification published by Microsoft. No cap.
Also โ using 'auto-import' will cause read only data which would normally be placed into the .rdata section to be placed into the .data section instead. Why? To work around a problem with consts that's described right here: http://www.cygwin.com/ml/cygwin/2004-09/msg01101.html
Using 'auto-import' generally will 'just work' โ but sometimes you may see this message:
"variable '<var>' can't be auto-imported. Please read the documentation for ld's "--enable-auto-import" for details."
This message occurs when some (sub)expression accesses an address ultimately given by the sum of two constants (Win32 import tables only allow one). ๐ญ Instances where this may occur include accesses to member fields of struct variables imported from a DLL, as well as using a constant index into an array variable imported from a DLL. Any multiword variable (arrays, structs, long long, etc) may trigger this error condition. However, regardless of the exact data type of the offending exported variable, ld will always detect it, issue the warning, and exit.
There are several ways to address this difficulty, regardless of the data type of the exported variable:
One way is to use --enable-runtime-pseudo-reloc switch. This leaves the task of adjusting references in your client code for runtime environment, so this method works only when runtime environment supports this feature. ๐ซถ
A second solution is to force one of the 'constants' to be a variable โ that is, unknown and un-optimizable at compile time. For arrays, there are two possibilities: a) make the indexee (the array's address) a variable, or b) make the 'constant' index a variable. Thus:
extern type extern_array[];
extern_array[1] -->
{ volatile type *t=extern_array; t[1] }
or
extern type extern_array[];
extern_array[1] -->
{ volatile int t=1; extern_array[t] }
For structs (and most other multiword data types) the only option is to make the struct itself (or the long long, or the ...) variable:
extern struct s extern_struct;
extern_struct.field -->
{ volatile struct s *t=&extern_struct; t->field }
or
extern long long extern_ll;
extern_ll -->
{ volatile long long * local_ll=&extern_ll; *local_ll }
A third method of dealing with this difficulty is to abandon 'auto-import' for the offending symbol and mark it with "__declspec(dllimport)". However, in practice that requires using compile-time #defines to indicate whether you are building a DLL, building client code that will link to the DLL, or merely building/linking to a static library. In making the choice between the various methods of resolving the 'direct address with constant offset' problem, you should consider typical real-world usage:
Original:
--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
printf("%d\n",arr[1]);
}
Solution 1:
--foo.h
extern int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
/* This workaround is for win32 and cygwin; do not "optimize" */
volatile int *parr = arr;
printf("%d\n",parr[1]);
}
Solution 2:
--foo.h
/* Note: auto-export is assumed (no __declspec(dllexport)) */
#if (defined(_WIN32) || defined(__CYGWIN__)) && \
!(defined(FOO_BUILD_DLL) || defined(FOO_STATIC))
#define FOO_IMPORT __declspec(dllimport)
#else
#define FOO_IMPORT
#endif
extern FOO_IMPORT int arr[];
--foo.c
#include "foo.h"
void main(int argc, char **argv){
printf("%d\n",arr[1]);
}
A fourth way to avoid this problem is to re-code your library to use a functional interface rather than a data interface for the offending variables (e.g. set_foo() and get_foo() accessor functions). [This option is specific to the i386 PE targeted port of the linker]
--disable-auto-importโ nope, do not attempt to do sophisticated linking of"_symbol"to"__imp__symbol"for DATA imports from DLLs. That's it, that's the whole vibe. [This option is specific to the i386 PE targeted port of the linker]--enable-runtime-pseudo-relocโ if your code contains expressions described in the--enable-auto-importsection (aka DATA imports from DLL with non-zero offset), this switch will create a vector of 'runtime pseudo relocations' which can be used by runtime environment to adjust references to such data in your client code. ๐ฆ [This option is specific to the i386 PE targeted port of the linker]--disable-runtime-pseudo-relocโ do not create pseudo relocations for non-zero offset DATA imports from DLLs. Bye. ๐ [This option is specific to the i386 PE targeted port of the linker]--enable-extra-pe-debugโ show additional debug info related to auto-import symbol thunking. Detective mode fr fr. ๐ [This option is specific to the i386 PE targeted port of the linker]--section-alignmentโ sets the section alignment. Sections in memory will always begin at addresses which are a multiple of this number. Defaults 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. (Yes, there is literally a space in the option name โ that's not a typo, bestie.) [This option is specific to the i386 PE targeted port of the linker]--subsystem which,--subsystem which:major,--subsystem which:major.minorโ specifies the subsystem under which your program will execute. The legal values for which are"native","windows","console","posix", and"xbox". You may optionally set the subsystem version also. Numeric values are also accepted for which. ๐ [This option is specific to the i386 PE targeted port of the linker]
The following options set flags in the "DllCharacteristics" field of the PE file header: [These options are specific to PE targeted ports of the linker]
--high-entropy-vaโ image is compatible with 64-bit address space layout randomization (ASLR). ๐--dynamicbaseโ the image base address may be relocated using address space layout randomization (ASLR). This feature was introduced with MS Windows Vista for i386 PE targets.--forceintegโ code integrity checks are enforced. ๐ฅ--nxcompatโ the image is compatible with the Data Execution Prevention. This feature was introduced with MS Windows XP SP2 for i386 PE targets.--no-isolationโ although the image understands isolation, do not isolate the image. ๐--no-sehโ the image does not use SEH. No SE handler may be called from this image.--no-bindโ do not bind this image.--wdmdriverโ the driver uses the MS Windows Driver Model.--tsawareโ the image is Terminal Server aware. โจ--insert-timestamp,--no-insert-timestampโ insert a real timestamp into the image. This is the default behaviour as it matches legacy code and it means that the image will work with other, proprietary tools. The problem with this default is that it will result in slightly different images being produced each time the same sources are linked. The option--no-insert-timestampcan be used to insert a zero value for the timestamp, this ensuring that binaries produced from identical sources will compare identically. Reproducible builds iconique behavior. ๐
The C6X uClinux target uses a binary format called DSBT to support shared libraries. Each shared library in the system needs to have a unique index; all executables use an index of 0. ๐
--dsbt-size sizeโ this option sets the number of entries in the DSBT of the current executable or shared library to size. The default is to create a table 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. Just so you know. ๐
The 68HC11 and 68HC12 linkers support specific options to control the memory bank switching mapping and trampoline code generation. Old school but still slaying.
--no-trampolineโ this option disables the generation of trampoline. By default a trampoline is generated for each far function which is called using a"jsr"instruction (this happens when a pointer to a far function is taken). ๐ง--bank-window nameโ this option indicates to the linker the name of the memory region in theMEMORYspecification 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 control which microMIPS instructions get used in code generated by the linker, like the stuff in the PLT or lazy binding stubs, or in relaxation. If--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 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 ofBALinstructions which meet relaxation conditions and are converted to equivalentJALXinstructions 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. ๐ซถ
โจ ENVIRONMENT โจ
okay so you can literally change how ld behaves with these environment variables: GNUTARGET, LDEMULATION, and COLLECT_NO_DEMANGLE.
GNUTARGETโ determines the input-file object format if you donโt use-b(or its synonym--format). Its value should be one of the BFD names for an input format. If there is noGNUTARGETin the environment,lduses the natural format of the target. IfGNUTARGETis set todefaultthen BFD attempts to discover the input format by examining binary input files; this method often succeeds, but there are potential ambiguities, since there is no method of ensuring that the magic number used to specify object-file formats is unique. However, the configuration procedure for BFD on each system places the conventional format for that system first in the search-list, so ambiguities are resolved in favor of convention. ๐ฆLDEMULATIONโ determines the default emulation if you donโt use the-moption. The emulation can affect various aspects of linker behaviour, particularly the default linker script. You can list the available emulations with the--verboseor-Voptions. If the-moption is not used, and theLDEMULATIONenvironment variable is not defined, the default emulation depends upon how the linker was configured. ๐ธCOLLECT_NO_DEMANGLEโ normally, the linker will default to demangling symbols. However, ifCOLLECT_NO_DEMANGLEis set in the environment, then it will default to not demangling symbols. This environment variable is used in a similar fashion by thegcclinker wrapper program. The default may be overridden by the--demangleand--no-demangleoptions. ๐
๐ SEE ALSO ๐
bestie, go read ar(1), nm(1), objcopy(1), objdump(1), readelf(1) and the Info entries for binutils and ld. iykyk ๐
๐ COPYRIGHT ๐
Copyright (c) 1991-2018 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". ๐
๐ and thatโs the whole LD(1) page, bestie โ brought to you by binutils-2.30, dated 2018-01-27. bye bestie! ๐
โจ
๐ฆ where this page comes from
- nixpkgs unstable: djgpp 12.2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms