macOS: @rpath, install_name, LC_RPATH
macOS 26.6.2(25G83)
ld, dyld
Install name
@executable_path, @loader_path, @rpath
LC_ID_DYLIB, LC_LOAD_DYLIB, LC_RPATH
For debugging purposes, it is useful to know the following:
- To view the install name of a shared library, use
otool -D <file> - To view the install name of dependent shared libraries, use
otool -L <file> - To view the RPATHs for locating dependent shared libraries using @rpath, use
otool -l <file> | grep LC_RPATH -A2 - To modify RPATHs, use
install_name_tool’s-rpath,-add_rpath, and-delete_rpathoptions.
Xcode
Build settings -> Linking - General
- DYLIB_INSTALL_NAME_BASE (Dynamic Library Install Name Base)
- Sets the base value for the internal
install path(LC) in a dynamic library. This will be combined with the_ID _DYLIB EXECUTABLEto form the full install path. Setting_PATH LDdirectly will override this setting. This setting defaults to the target’s_DYLIB _INSTALL _NAME INSTALL. It is ignored when building any product other than a dynamic library._PATH $(DYLIB_INSTALL_NAME_BASE_$(LLVM_TARGET_TRIPLE_VENDOR))
- Sets the base value for the internal
- LD
_DYLIB _INSTALL _NAME (Dynamic Library Install Name) - Sets an internal
install path(LC) in a dynamic library. Any clients linked against the library will record that path as the way_ID _DYLIB dyldshould locate this library. If this option is not specified, then the-opath will be used. This setting is ignored when building any product other than a dynamic library. $(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)
- Sets an internal
- LD
_RUNPATH _SEARCH _PATHS (Runpath Search Paths) - This is a list of paths to be added to the
runpathsearch path list for the image being created. At runtime,dylduses therunpathwhen searching for dylibs whose load path begins with@rpath/.
- This is a list of paths to be added to the
CMake
install_name<- INSTALL_NAME_DIR, MACOSX_RPATH (boolean,@rpath)- build tree
- BUILD_WITH_INSTALL_NAME_DIR (boolean)
- build tree
LC_RPATH- CMAKE_SKIP_RPATH (boolean)
- build tree
- BUILD_WITH_INSTALL_RPATH (boolean)
- SKIP_BUILD_RPATH (boolean)
- BUILD_RPATH
- BUILD_RPATH_USE_ORIGIN ¿
- install tree
- CMAKE_SKIP_INSTALL_RPATH (boolean)
- INSTALL_RPATH
- INSTALL_RPATH_USE_LINK_PATH (boolean)
- INSTALL_REMOVE_ENVIRONMENT_RPATH ¿
Meson
meson compile
- AppleDynamicLinker.get_soname_args
- install_name = ['@rpath/', prefix, shlib_name]
meson install
- minstall.run
- do_install -> install_targets
- fix_rpath
- do_install -> install_targets
- depfixer.fix_rpath
- depfixer.fix_darwin
- rpath: new <- new_rpath + ( old - remove )
- install_name_tool: -id, -change (install_name_mappings), -add_rpath, -delete_rpath
- depfixer.fix_darwin
Reference
- Dynamic Library Identification
- Dynamic Library Programming Topics
- Friday Q&A 2009-11-06: Linking and Install Names
- Upcoming in CMake 2.8.12: OSX RPath Support
- CMake Community Wiki - RPATH handling
- cmake-policies(7)
- cmake-variables(7)
Appendix
CMake
3.16
- The
BUILD_RPATHandINSTALL_RPATHtarget properties now supportgenerator expressions. - The
INSTALL_REMOVE_ENVIRONMENT_RPATHtarget property was added to remove compiler-definedRPATHentries from a target. This property is initialized by theCMAKE_INSTALL_REMOVE_ENVIRONMENT_RPATHvariable. RPATHentries are properly escaped in the generated CMake scripts used for installation. See policyCMP0095.
3.14
A CMAKE_BUILD_RPATH_USE_ORIGIN variable and corresponding BUILD_RPATH_USE_ORIGIN target property were added to enable use of relative runtime paths (RPATHs). This helps achieving relocatable and reproducible builds that are invariant of the build directory.
3.9.0 (July 18, 2017)
CMP0068: RPATH settings on macOS do not affect install_name.
CMake 3.9 and newer remove any effect the following settings may have on the install_name of a target on macOS:
BUILD_WITH_INSTALL_RPATHtarget propertySKIP_BUILD_RPATHtarget propertyCMAKE_SKIP_RPATHvariableCMAKE_SKIP_INSTALL_RPATHvariable
BUILD_WITH_INSTALL_RPATH: RPATH to INSTALL_RPATH.
BUILD_WITH_INSTALL_NAME_DIR: install_name to INSTALL_NAME_DIR.
3.8.0
A BUILD_RPATH target property and corresponding CMAKE_BUILD_RPATH variable were added to support custom RPATH locations to be added to binaries in the build tree.
3.0.0 (June 10, 2014)
CMP0042: On OS X, CMake learned to enable behavior specified by the MACOSX_RPATH target property by default. This activates use of @rpath for runtime shared library searches.
- The OLD behavior of this policy was removed in CMake version 4.0.
MACOSX_RPATH: Whether to use rpaths on Mac OS X. When this property is set to true, the directory portion of the"install_name" field of shared libraries will default to "@rpath". Runtime paths will also be embedded in binaries using this target. This property is initialized by the value of the variableCMAKE_MACOSX_RPATHif it is set when a target is created.
2.8.12 (October 8, 2013)
Introduced: Support for RPATH under OSX
see: post by Clinton Stimpson about using RPATH on OSX, http://www.kitware.com/blog/home/post/510
Notable target properties are MACOSX_RPATH and INSTALL_RPATH. MACOSX_RPATH is a flag that simply turns @rpath on or off for a target. In the past, INSTALL_NAME_DIR has been used to control install names, but there shouldn’t be a need to do this anymore. However, if it is still used, it overrides the MACOSX_RPATH flag.
~ 2.8.11
There are a few properties used to specify RPATH rules.
INSTALL_RPATHis a semicolon-separated list specifying the rpath to use in installed targets (for platforms that support it).
INSTALL_RPATH_USE_LINK_PATHis a boolean that if set to true will append directories in the linker search path and outside the project to the INSTALL_RPATH.
SKIP_BUILD_RPATHis a boolean specifying whether to skip automatic generation of an rpath allowing the target to run from the build tree.
BUILD_WITH_INSTALL_RPATHis a boolean specifying whether to link the target in the build tree with the INSTALL_RPATH. This takes precedence over SKIP_BUILD_RPATH and avoids the need for relinking before installation.
INSTALL_NAME_DIRis a string specifying the directory portion of the "install_name" field of shared libraries on Mac OSX to use in the installed targets.
When the target is created the values of the variables
CMAKE_INSTALL_RPATH,CMAKE_INSTALL_RPATH_USE_LINK_PATH,CMAKE_SKIP_BUILD_RPATH,CMAKE_BUILD_WITH_INSTALL_RPATH, andCMAKE_INSTALL_NAME_DIRare used to initialize these properties.
LD, DYLD
LD(1)
ld(1) General Commands Manual ld(1)
NAME
ld – linker
SYNOPSIS
ld files... [options] [-o outputfile]
DESCRIPTION
The ld command combines several object files and libraries, resolves references, and produces an output file. ld
can produce a final linked image (executable, dylib, or bundle), or with the -r option, produce another object
file. If the -o option is not used, the output file produced is named "a.out".
Universal
The linker accepts universal (multiple-architecture) input files, but always creates a "thin" (single-
architecture), standard Mach-O output file. The architecture for the output file is specified using the -arch
option. If this option is not used, ld attempts to determine the output architecture by examining the object files
in command line order. The first "thin" architecture determines that of the output file. If no input object file
is a "thin" file, the native 32-bit architecture for the host is used.
Usually, ld is not used directly. Instead the compiler driver invokes ld. The compiler driver can be passed
multiple -arch options and it will create a universal final linked image by invoking ld multiple times and then
running lipo(1) merge the outputs into a universal file.
Layout
The object files are loaded in the order in which they are specified on the command line. The segments and the
sections in those segments will appear in the output file in the order they are encountered in the object files
being linked. All zero fill sections will appear after all non-zero fill sections in their segments.
Libraries
A static library (aka static archive) is a collection of .o files with a table of contents that lists the global
symbols in the .o files. ld will only pull .o files out of a static library if needed to resolve some symbol
reference. Unlike traditional linkers, ld will continually search a static library while linking. There is no need
to specify a static library multiple times on the command line.
A dynamic library (aka dylib or framework) is a final linked image. Putting a dynamic library on the command line
causes two things: 1) The generated final linked image will have encoded that it depends on that dynamic library.
2) Exported symbols from the dynamic library are used to resolve references.
Both dynamic and static libraries are searched as they appear on the command line.
Search paths
ld maintains a list of directories to search for a library or framework to use. The default library search path is
/usr/lib then /usr/local/lib. The -L option will add a new library search path. The default framework search path
is /Library/Frameworks then /System/Library/Frameworks. (Note: previously, /Network/Library/Frameworks was at the
end of the default path. If you need that functionality, you need to explicitly add
-F/Network/Library/Frameworks). The -F option will add a new framework search path. The -Z option will remove the
standard search paths. The -syslibroot option will prepend a prefix to all search paths.
Two-level namespace
By default all references resolved to a dynamic library record the library to which they were resolved. At runtime,
dyld uses that information to directly resolve symbols. The alternative is to use the -flat_namespace option.
With flat namespace, the library is not recorded. At runtime, dyld will search each dynamic library in load order
when resolving symbols. This is slower, but more like how other operating systems resolve symbols.
Indirect dynamic libraries
If the command line specifies to link against dylib A, and when dylib A was built it linked against dylib B, then B
is considered an indirect dylib. When linking for two-level namespace, ld does not look at indirect dylibs, except
when re-exported by a direct dylibs. On the other hand when linking for flat namespace, ld does load all indirect
dylibs and uses them to resolve references. Even though indirect dylibs are specified via a full path, ld first
uses the specified search paths to locate each indirect dylib. If one cannot be found using the search paths, the
full path is used.
Dynamic libraries undefines
When linking for two-level namespace, ld does not verify that undefines in dylibs actually exist. But when linking
for flat namespace, ld does check that all undefines from all loaded dylibs have a matching definition. This is
sometimes used to force selected functions to be loaded from a static library.
OPTIONS
Options that control the kind of output
-execute
The default. Produce a mach-o main executable that has file type MH_EXECUTE.
-dylib Produce a mach-o shared library that has file type MH_DYLIB.
-bundle
Produce a mach-o bundle that has file type MH_BUNDLE.
-r Merges object files to produce another mach-o object file with file type MH_OBJECT.
-dylinker
Produce a mach-o dylinker that has file type MH_DYLINKER. Only used when building dyld.
-dynamic
The default. Implied by -dylib, -bundle, or -execute
-static
Produces a mach-o file that does not use the dyld. Only used building the kernel.
-preload
Produces a mach-o file in which the mach_header, load commands, and symbol table are not in any segment.
This output type is used for firmware or embedded development where the segments are copied out of the
mach-o into ROM/Flash.
-arch arch_name
Specifies which architecture (e.g. ppc, ppc64, i386, x86_64) the output file should be.
-o path
Specifies the name and location of the output file. If not specified, `a.out' is used.
Options that control libraries
-lx This option tells the linker to search for libx.dylib or libx.a in the library search path. If string x is
of the form y.o, then that file is searched for in the same places, but without prepending `lib' or
appending `.a' or `.dylib' to the filename.
-needed-lx
This is the same as the -lx but means to really link with the dylib even if no symbols are used from it.
Thus, it can be used suppress warnings about unused dylibs.
-reexport-lx
This is the same as the -lx but specifies that the all symbols in library x should be available to clients
linking to the library being created. This was previously done with a separate -sub_library option.
-upward-lx
This is the same as the -lx but specifies that the dylib is an upward dependency.
-hidden-lx
This is the same as the -lx for locating a static library, but treats all global symbols from the static
library as if they are visibility hidden. Useful when building a dynamic library that uses a static
library but does not want to export anything from that static library.
-weak-lx
This is the same as the -lx but forces the library and all references to it to be marked as weak imports.
That is, the library is allowed to be missing at runtime.
-assert-weak-lx
This is the same as the -weak-l but verifies that all references were marked as weak imports, instead of
forcing it.
-delay-lx
This is the same as the -lx but specifies that the dylib should be delay initialized.
-needed_library path_to_dylib
This is the same as placing path_to_dylib on the link line but means to really link with the dylib even if
no symbols are used from it. Thus, it can be used suppress warnings about unused dylibs.
-reexport_library path_to_library
This is the same as listing a file name path to a library on the link line and it specifies that the all
symbols in library path should be available to clients linking to the library being created. This was
previously done with a separate -sub_library option.
-upward_library path_to_library
This is the same as listing a file name path to a library on the link line but also marks the dylib as an
upward dependency.
-weak_library path_to_library
This is the same as listing a file name path to a library on the link line except that it forces the
library and all references to it to be marked as weak imports.
-assert_weak_library path_to_library
This is the same as the -weak_library but verifies that all references were marked as weak imports, instead
of forcing it.
-delay_library path_to_library
This is the same as listing a file name path to a library on the link line except that will mark the dylib
to be delay initialized.
-Ldir Add dir to the list of directories in which to search for libraries. Directories specified with -L are
searched in the order they appear on the command line and before the default search path. In Xcode4 and
later, there can be a space between the -L and directory.
-Z Do not search the standard directories when searching for libraries and frameworks.
-syslibroot rootdir
Prepend rootdir to all search paths when searching for libraries or frameworks.
-search_paths_first
This is now the default (in Xcode4 tools). When processing -lx the linker now searches each directory in
its library search paths for `libx.dylib' then `libx.a' before the moving on to the next path in the
library search path.
-search_dylibs_first
Changes the searching behavior for libraries. The default is that when processing -lx the linker searches
each directory in its library search paths for `libx.dylib' then `libx.a'. This option changes the
behavior to first search for a file of the form `libx.dylib' in each directory in the library search path,
then a file of the form `libx.a' is searched for in the library search paths. This option restores the
search behavior of the linker prior to Xcode4.
-framework name[,suffix]
This option tells the linker to search for `name.framework/name' the framework search path. If the
optional suffix is specified the framework is first searched for the name with the suffix and then without
(e.g. look for `name.framework/name_suffix' first, if not there try `name.framework/name').
-needed_framework name[,suffix]
This is the same as the -framework name[,suffix] but means to really link with the framework even if no
symbols are used from it. Thus, it can be used suppress warnings about unused dylibs.
-weak_framework name[,suffix]
This is the same as the -framework name[,suffix] but forces the framework and all references to it to be
marked as weak imports. Note: due to a clang optimizations, if functions are not marked weak, the compiler
will optimize out any checks if the function address is NULL.
-assert_weak_framework name[,suffix]
This is the same as the -weak_framework but verifies that all references were marked as weak imports,
instead of forcing it.
-reexport_framework name[,suffix]
This is the same as the -framework name[,suffix] but also specifies that the all symbols in that framework
should be available to clients linking to the library being created. This was previously done with a
separate -sub_umbrella option.
-upward_framework name[,suffix]
This is the same as the -framework name[,suffix] but also specifies that the framework is an upward
dependency.
-delay_framework name[,suffix]
This is the same as the -framework name[,suffix] but also specifies that the framework should be delay
initialized.
-Fdir Add dir to the list of directories in which to search for frameworks. Directories specified with -F are
searched in the order they appear on the command line and before the default search path. In Xcode4 and
later, there can be a space between the -F and directory.
-all_load
Loads all members of static archive libraries.
-ObjC Loads all members of static archive libraries that implement an Objective-C class, category or a Swift
struct, class or an extension.
-force_load path_to_archive
Loads all members of the specified static archive library. Note: -all_load forces all members of all
archives to be loaded. This option allows you to target a specific archive.
-load_hidden path_to_archive
Uses specified static library as usual, but treats all global symbols from the static library to as if they
are visibility hidden. Useful when building a dynamic library that uses a static library but does not want
to export anything from that static library.
-image_suffix suffix
Search for libraries and frameworks with suffix and then without.
Options that control additional content
-sectcreate segname sectname file
The section sectname in the segment segname is created from the contents of file file. If there's a section
(segname,sectname) from any other input, the linker will append the content from the file to that section.
-add_empty_section segname sectname
An empty section named sectname in the segment segname. If any of the inputs contains a section
(segname,sectname), that section will be included in the output, and this option will be ignored.
-add_ast_path file
The linker will add a N_AST stab symbol to the output file where the string is the path pointed by file and
its values is the modification time of the file.
-filelist file[,dirname]
Specifies that the linker should link the files listed in file. This is an alternative to listing the
files on the command line. The file names are listed one per line separated only by newlines. (Spaces and
tabs are assumed to be part of the file name.) If the optional directory name, dirname is specified, it is
prepended to each name in the list file.
-dtrace file
Enables dtrace static probes when producing a final linked image. The file file must be a DTrace script
which declares the static probes.
Options that control optimizations
-dead_strip
Remove functions and data that are unreachable by the entry point or exported symbols.
-order_file file
Alters the order in which functions and data are laid out. For each section in the output file, any symbol
in that section that are specified in the order file file is moved to the start of its section and laid out
in the same order as in the order file file. Order files are text files with one symbol name per line.
Lines starting with a # are comments. A symbol name may be optionally preceded with its object file leaf
name and a colon (e.g. foo.o:_foo). This is useful for static functions/data that occur in multiple files.
A symbol name may also be optionally preceded with the architecture (e.g. ppc:_foo or ppc:foo.o:_foo).
This enables you to have one order file that works for multiple architectures. Literal c-strings may be
ordered by by quoting the string (e.g. "Hello, world\n") in the order file.
-no_order_inits
When the -order_file option is not used, the linker lays out functions in object file order and it moves
all initializer routines to the start of the __text section and terminator routines to the end. Use this
option to disable the automatic rearrangement of initializers and terminators.
-platform_version platform min_version sdk_version
This is set to indicate the platform, oldest supported version of that platform that output is to be used
on, and the SDK that the output was built against. platform is a numeric value as defined in <mach-
o/loader.h>, or it may be one of the following strings:
• macos
• ios
• tvos
• watchos
• bridgeos
• visionos
• xros
• mac-catalyst
• ios-simulator
• tvos-simulator
• watchos-simulator
• visionos-simulator
• xros-simulator
• driverkit
• firmware
• sepOS
Specifying a newer min or SDK version enables the linker to assume features of that OS or SDK in the output
file. The format of min_version and sdk_version is a version number such as 10.13 or 10.14
-macos_version_min version
This is set to indicate the oldest macOS version that that the output is to be used on. Specifying a later
version enables the linker to assumes features of that OS in the output file. The format of version is a
macOS version number such as 10.9 or 10.14
-ios_version_min version
This is set to indicate the oldest iOS version that that the output is to be used on. Specifying a later
version enables the linker to assumes features of that OS in the output file. The format of version is an
iOS version number such as 3.1 or 4.0
-image_base address
Specifies the preferred load address for a dylib or bundle. The argument address is a hexadecimal number
with an optional leading 0x. By choosing non-overlapping address for all dylibs and bundles that a program
loads, launch time can be improved because dyld will not need to "rebase" the image (that is, adjust
pointers within the image to work at the loaded address). It is often easier to not use this option, but
instead use the rebase(1) tool, and give it a list of dylibs. It will then choose non-overlapping
addresses for the list and rebase them all. When building a position independent executable, this option
will be ignored. This option is also called -seg1addr for compatibility.
-no_implicit_dylibs
When creating a two-level namespace final linked image, normally the linker will hoist up public dylibs
that are implicitly linked to make the two-level namespace encoding more efficient for dyld. For example,
Cocoa re-exports AppKit and AppKit re-exports Foundation. If you link with -framework Cocoa and use a
symbol from Foundation, the linker will implicitly add a load command to load Foundation and encode the
symbol as coming from Foundation. If you use this option, the linker will not add a load command for
Foundation and encode the symbol as coming from Cocoa. Then at runtime dyld will have to search Cocoa and
AppKit before finding the symbol in Foundation.
-no_zero_fill_sections
By default the linker moves all zero fill sections to the end of the __DATA segment and configures them to
use no space on disk. This option suppresses that optimization, so zero-filled data occupies space on disk
in a final linked image.
-merge_zero_fill_sections
Causes all zero-fill sections in the __DATA segment to be merged into one __zerofill section.
-no_branch_islands
Disables linker creation of branch islands which allows images to be created that are larger than the
maximum branch distance. Useful with -preload when code is in multiple sections but all are within the
branch range.
-verbose_branch_islands
Prints size information about the inserted branch islands and their code size overhead.
-O0 Disables certain optimizations and layout algorithms to optimize build time. This option should be used
with debug builds to speed up incremental development. The exact implementation might change to match the
intent.
-reproducible
By default output content will be deterministic, but small changes in input files such as a compilation
time might affect certain data structures in the linked binary. This option instructs ld to create a
reproducible output binary by ignoring certain input properties or using alternative algorithms.
Options when creating a dynamic library (dylib)
-install_name name
Sets an internal "install path" (LC_ID_DYLIB) in a dynamic library. Any clients linked against the library
will record that path as the way dyld should locate this library. If this option is not specified, then
the -o path will be used. This option is also called -dylib_install_name for compatibility.
-compatibility_version number
Specifies the compatibility version number of the library. When a library is loaded by dyld, the
compatibility version is checked and if the program's version is greater that the library's version, it is
an error. The format of number is X[.Y[.Z]] where X must be a positive non-zero number less than or equal
to 65535, and .Y and .Z are optional and if present must be non-negative numbers less than or equal to 255.
If the compatibility version number is not specified, it has a value of 0 and no checking is done when the
library is used. This option is also called -dylib_compatibility_version for compatibility.
-current_version number
Specifies the current version number of the library. The current version of the library can be obtained
programmatically by the user of the library so it can determine exactly which version of the library it is
using. The format of number is X[.Y[.Z]] where X must be a positive non-zero number less than or equal to
65535, and .Y and .Z are optional and if present must be non-negative numbers less than or equal to 255.
If the version number is not specified, it has a value of 0. This option is also called
-dylib_current_version for compatibility.
Options when creating a main executable
-pie This makes a special kind of main executable that is position independent (PIE). On Mac OS X 10.5 and
later, the OS the OS will load a PIE at a random address each time it is executed. You cannot create a PIE
from .o files compiled with -mdynamic-no-pic. That means the codegen is less optimal, but the address
randomization adds some security. When targeting Mac OS X 10.7 or later PIE is the default for main
executables.
-no_pie
Do not make a position independent executable (PIE). This is the default, when targeting 10.6 and earlier.
-pagezero_size size
By default the linker creates an unreadable segment starting at address zero named __PAGEZERO. Its
existence will cause a bus error if a NULL pointer is dereferenced. The argument size is a hexadecimal
number with an optional leading 0x. If size is zero, the linker will not generate a page zero segment. By
default on 32-bit architectures the page zero size is 4KB. On 64-bit architectures, the default size is
4GB.
-stack_size size
Specifies the maximum stack size for the main thread in a program. Without this option a program has a 8MB
stack. The argument size is a hexadecimal number with an optional leading 0x. The size should be a
multiple of the architecture's page size (4KB or 16KB).
-allow_stack_execute
Marks executable so that all stacks in the task will be given stack execution privilege. This includes
pthread stacks. This option is only valid when targeting architectures that support stack execution (i.e.
Intel).
-export_dynamic
Preserves all global symbols in main executables during LTO. Without this option, Link Time Optimization
is allowed to inline and remove global functions. This option is used when a main executable may load a
plug-in which requires certain symbols from the main executable.
Options when creating a bundle
-bundle_loader executable
This specifies the executable that will be loading the bundle output file being linked. Undefined symbols
from the bundle are checked against the specified executable like it was one of the dynamic libraries the
bundle was linked with.
Options when creating an object file
-keep_private_externs
Don't turn private external (aka visibility=hidden) symbols into static symbols, but rather leave them as
private external in the resulting object file.
-d Force definition of common symbols. That is, transform tentative definitions into real definitions.
Options that control symbol resolution
-exported_symbols_list filename
The specified filename contains a list of global symbol names that will remain as global symbols in the
output file. All other global symbols will be treated as if they were marked as __private_extern__ (aka
visibility=hidden) and will not be global in the output file. The symbol names listed in filename must be
one per line. Leading and trailing white space are not part of the symbol name. Lines starting with # are
ignored, as are lines with only white space. Some wildcards (similar to shell file matching) are
supported. The * matches zero or more characters. The ? matches one character. [abc] matches one
character which must be an 'a', 'b', or 'c'. [a-z] matches any single lower case letter from 'a' to 'z'.
-exported_symbol symbol
The specified symbol is added to the list of global symbols names that will remain as global symbols in the
output file. This option can be used multiple times. For short lists, this can be more convenient than
creating a file and using -exported_symbols_list.
-no_exported_symbols
Useful for main executable that don't have plugins and thus need no symbol exports.
-unexported_symbols_list file
The specified filename contains a list of global symbol names that will not remain as global symbols in the
output file. The symbols will be treated as if they were marked as __private_extern__ (aka
visibility=hidden) and will not be global in the output file. The symbol names listed in filename must be
one per line. Leading and trailing white space are not part of the symbol name. Lines starting with # are
ignored, as are lines with only white space. Some wildcards (similar to shell file matching) are
supported. The * matches zero or more characters. The ? matches one character. [abc] matches one
character which must be an 'a', 'b', or 'c'. [a-z] matches any single lower case letter from 'a' to 'z'.
-unexported_symbol symbol
The specified symbol is added to the list of global symbols names that will not remain as global symbols in
the output file. This option can be used multiple times. For short lists, this can be more convenient
than creating a file and using -unexported_symbols_list.
-reexported_symbols_list file
The specified filename contains a list of symbol names that are implemented in a dependent dylib and should
be re-exported through the dylib being created.
-alias symbol_name alternate_symbol_name
Create an alias named alternate_symbol_name for the symbol symbol_name. By default the alias symbol has
global visibility. This option was previous the -idef:indir option.
-alias_list filename
The specified filename contains a list of aliases. The symbol name and its alias are on one line, separated
by whitespace. Lines starting with # are ignored.
-flat_namespace
Alters how symbols are resolved at build time and runtime. With -two_levelnamespace (the default), the
linker only searches dylibs on the command line for symbols, and records in which dylib they were found.
With -flat_namespace, the linker searches all dylibs on the command line and all dylibs those original
dylibs depend on. The linker does not record which dylib an external symbol came from, so at runtime dyld
again searches all images and uses the first definition it finds. In addition, any undefines in loaded
flat_namespace dylibs must be resolvable at build time.
-u symbol_name
Specified that symbol symbol_name must be defined for the link to succeed. This is useful to force
selected functions to be loaded from a static library.
-U symbol_name
Specified that it is ok for symbol_name to have no definition. With -two_levelnamespace, the resulting
symbol will be marked dynamic_lookup which means dyld will search all loaded images.
-undefined treatment
Specifies how undefined symbols are to be treated. Options are: error, warning, suppress, or
dynamic_lookup. The default is error. Note: dynamic_lookup that depends on lazy binding will not work with
chained fixups.
-rpath path
Add path to the runpath search path list for image being created. At runtime, dyld uses the runpath when
searching for dylibs whose load path begins with @rpath/.
-commons treatment
Specifies how commons (aka tentative definitions) are resolved with respect to dylibs. Options are:
ignore_dylibs, error. The default is ignore_dylibs which means the linker will turn a tentative definition
in an object file into a real definition and not even check dylibs for conflicts. The error option means
the linker should issue an error whenever a tentative definition in an object file conflicts with an
external symbol in a linked dylib. See also -warn_commons.
Options for introspecting the linker
-why_load
Log why each object file in a static library is loaded. That is, what symbol was needed. Also called
-whyload for compatibility.
-why_live symbol_name
Logs a chain of references to symbol_name. Only applicable with -dead_strip . It can help debug why
something that you think should be dead strip removed is not removed. See -exported_symbols_list for
syntax and use of wildcards.
-print_statistics
Logs information about the amount of memory and time the linker used.
-t Logs each file (object, archive, or dylib) the linker loads. Useful for debugging problems with search
paths where the wrong library is loaded.
-order_file_statistics
Logs information about the processing of a -order_file.
-map map_file_path
Writes a map file to the specified path which details all symbols and their addresses in the output image.
Options for controlling symbol table optimizations
-S Do not put debug information (STABS or DWARF) in the output file.
-x Do not put non-global symbols in the output file's symbol table. Non-global symbols are useful when
debugging and getting symbol names in back traces, but are not used at runtime. If -x is used with -r non-
global symbol names are not removed, but instead replaced with a unique, dummy name that will be
automatically removed when linked into a final linked image. This allows dead code stripping, which uses
symbols to break up code and data, to work properly and provides the security of having source symbol names
removed.
-non_global_symbols_strip_list filename
The specified filename contains a list of non-global symbol names that should be removed from the output
file's symbol table. All other non-global symbol names will remain in the output files symbol table. See
-exported_symbols_list for syntax and use of wildcards.
-non_global_symbols_no_strip_list filename
The specified filename contains a list of non-global symbol names that should be remain in the output
file's symbol table. All other symbol names will be removed from the output file's symbol table. See
-exported_symbols_list for syntax and use of wildcards.
-oso_prefix prefix-path
When generating the debug map, the linker will remove the specified prefix-path from the path in OSO
symbols. This can be used so to help build servers generate identical binaries. If '.' is passed as
argument, the linker will expand the argument to the current working directory.
Options for Bitcode build flow
-bitcode_bundle
Generates an embedded bitcode bundle in the output binary. The bitcode bundle is embedded in __LLVM,
__bundle section. This option requires all the object files, static libraries and user frameworks/dylibs
contain bitcode. Note: not all the linker options are supported to use together with -bitcode_bundle.
-bitcode_hide_symbols
Specifies this option together with -bitcode_bundle to hide all non-exported symbols from output bitcode
bundle. The hide symbol process might not be reversible. To obtain a reverse mapping file to recover all
the symbols, use -bitcode_symbol_map option.
-bitcode_symbol_map path
Specifies the output for bitcode symbol reverse mapping (.bcsymbolmap). If path is an existing directory,
UUID.bcsymbolmap will be written to that directory. Otherwise, the reverse map will be written to a file
at path.
Rarely used Options
@response_file_path
Inserts contents of file at response_file_path into arguments. This allows for linker command line args to
be store in a file. Note: ld is normally invoked through clang, and clang also interprets @file on the
command line. To have clang ignore the @file and pass it through to ld, use -Wl,@file.
-v Prints the version of the linker.
-adhoc_codesign
Directs the linker to add an ad-hoc codesignature to the output file. The default for Apple Silicon
binaries is to be ad-hoc codesigned.
-no_adhoc_codesign
Directs the linker to not add ad-hoc codesignature to the output file, even for Apple Silicon binaries.
-data_const
By default the linker moves some data sections into __DATA_CONST if it knows the target OS version supports
that. This option option overrides the default behavior and forces the use of __DATA_CONST.
-no_data_const
By default the linker moves some data sections into __DATA_CONST if it knows the target OS version supports
that. This option option overrides the default behavior and forces the linker to never move sections to
__DATA_CONST.
-const_selrefs
By default the linker moves __objc_selrefs section into __DATA_CONST if it knows the target OS version
supports that. This option option overrides the default behavior and forces __objc_selrefs being in
__DATA_CONST. Note this only applies if the __DATA_CONST segment is enabled. See -data_const for more
information.
-no_const_selrefs
By default the linker moves __objc_selrefs section into __DATA_CONST if it knows the target OS version
supports that. This option option overrides the default behavior and keeps the __objc_selrefs section in
__DATA.
-version_details
Prints the version info about the linker in JSON
-no_weak_imports
Error if any symbols are weak imports (i.e. allowed to be unresolved (NULL) at runtime). Useful for config
based projects that assume they are built and run on the same OS version.
-no_deduplicate
Don't run deduplication pass in linker
-verbose_deduplicate
Prints names of functions that are eliminated by deduplication and total code savings size.
-no_inits
Error if the output contains any static initializers
-no_warn_inits
Do not warn if the output contains any static initializers
-warn_duplicate_libraries
Warn if the input contains duplicate library options.
-no_warn_duplicate_libraries
Do not warn if the input contains duplicate library options.
-no_warn_reduced_section_align
Do not warn when an input section's alignment exceeds its segment's maximum alignment and is reduced to
match the segment alignment.
-debug_variant
Do not warn about issues that are only problems for binaries shipping to customers.
-unaligned_pointers treatment
Specifies how unaligned pointers in __DATA segments should be handled. Options are: 'warning', 'error', or
'suppress'. The default for arm64e is 'error' and for all other architectures it is 'suppress'.
-dirty_data_list filename
Specifies a file containing the names of data symbols likely to be dirtied. If the linker is creating a
__DATA_DIRTY segment, those symbols will be moved to that segment.
-max_default_common_align value
Any common symbols (aka tentative definitions, or uninitialized (zeroed) variables) that have no explicit
alignment are normally aligned to their next power of two size (e.g. a 240 byte array is 256 aligned).
This option lets you reduce the max alignment. For instance, a value of 0x40 would reduce the alignment
for a 240 byte array to 64 bytes (instead of 256). The value specified must be a hexadecimal power of two
If -max_default_common_align is not used, the default alignment is already limited to 0x8 (2^3) bytes for
-preload and 0x8000 (2^15) for all other output types.
-move_to_rw_segment segment_name filename
Moves data symbols to another segment. The command line option specifies the target segment name and a
path to a file containing a list of symbols to move. Comments can be added to the symbol file by starting
a line with a #. If there are multiple instances of a symbol name (for instance a "static int foo=5;" in
multiple files) the symbol name in the symbol list file can be prefixed with the object file name (e.g.
"init.o:_foo") to move a specific instance.
-move_to_ro_segment segment_name filename
Moves code symbols to another segment. The command line option specifies the target segment name and a
path to a file containing a list of symbols to move. Comments can be added to the symbol file by starting
a line with a #. If there are multiple instances of a symbol name (for instance a "static int foo() {}" in
multiple files) the symbol name in the symbol list file can be prefixed with the object file name (e.g.
"init.o:_foo") to move a specific instance.
-rename_section orgSegment orgSection newSegment newSection
Renames section orgSegment/orgSection to newSegment/newSection.
-rename_segment orgSegment newSegment
Renames all sections with orgSegment segment name to have newSegment segment name.
-trace_symbol_layout
For using in debugging -rename_section, -rename_segment, -move_to_ro_segment, and -move_to_rw_segment.
This option prints out a line show where and why each symbol was moved. Note: These options do chain. For
each symbol, the linker first checks -move_to_ro_segment and -move_to_rw_segment. Next it applies any
-rename_section options, and lastly and -rename_segment options.
-trace_symbol_layout_file symbol_layout_file_path
This is the same as -trace_symbol_layout, but accepts a symbol_layout_file_path to write the trace data to.
-trace_implicit_libraries
Debug option to track down unexpected library dependencies. Logs libraries linked implicitly through auto-
linking hints (showing which input files contain the hints) and indirect libraries re-exported by
explicitly linked libraries.
-trace_implicit_library name_substring
This is the same as -trace_implicit_libraries, but accepts a name_substring to trace only a subset of
libraries.
-section_order segname colon_separated_section_list
Only for use with -preload, -dylinker, -static, or with -platform_version "firmware"/"sepOS". Specifies
the order in which the linker should lay out the sections for the specified segment. For example:
"-section_order __ROM __text:__const:__cstring". The specified sections are the placed first in the
segment. The remaining unspecified sections are ordered as they would have been if -section_order was not
specified.
-segment_order colon_separated_segment_list
Only for use with -preload, -static, or with -platform_version "firmware". Specifies the order in which the
linker should lay out the segments. For example: "-segment_order __ROM:__ROM2:__RAM". All segments should
be specified.
-allow_heap_execute
Normally i386 main executables will be marked so that the Mac OS X 10.7 and later kernel will only allow
pages with the x-bit to execute instructions. This option overrides that behavior and allows instructions
on any page to be executed.
-application_extension
Specifies that the code is being linked for use in an application extension. The linker will then validate
that any dynamic libraries linked against are safe for use in application extensions.
-no_application_extension
Specifies that the code is being linked is not safe for use in an application extension. For instance, can
be used when creating a framework that should not be used in an application extension.
-fatal_warnings
Causes the linker to exit with a non-zero value if any warnings were emitted.
-no_eh_labels
Normally in -r mode, the linker produces .eh labels on all FDEs in the __eh_frame section. This option
suppresses those labels. Those labels are not needed by the Mac OS X 10.6 linker but are needed by earlier
linker tools.
-warn_compact_unwind
When producing a final linked image, the linker processes the __eh_frame section and produces an
__unwind_info section. Most FDE entries in the __eh_frame can be represented by a 32-bit value in the
__unwind_info section. The option issues a warning for any function whose FDE cannot be expressed in the
compact unwind format.
-warn_weak_exports
Issue a warning if the resulting final linked image contains weak external symbols. Such symbols require
dyld to do extra work at launch time to coalesce those symbols.
-no_weak_exports
Issue an erro if the resulting final linked image contains weak external symbols. Such symbols require dyld
to do extra work at launch time to coalesce those symbols.
-warn_unused_dylibs
Warn about dylibs that are linked by no symbols are used from them.
-no_warn_unused_dylibs
Don't warn about dylibs that are linked by no symbols are used from them.
-dead_strip_dylibs
Remove dylibs that are unreachable by the entry point or exported symbols. That is, suppresses the
generation of load command commands for dylibs which supplied no symbols during the link. This option
should not be used when linking against a dylib which is required at runtime for some indirect reason such
as the dylib has an important initializer.
-allow_sub_type_mismatches
Normally the linker considers different cpu-subtype for ARM (e.g. armv4t and armv6) to be different
different architectures that cannot be mixed at build time. This option relaxes that requirement, allowing
you to mix object files compiled for different ARM subtypes.
-no_uuid
Do not generate an LC_UUID load command in the output file. Be warned that binaries without UUIDs may
cause the debugger and crash reporting tools to be unable to track and inspect the binary.
-random_uuid
Generate a random LC_UUID load command in the output file. By default the linker generates the UUID of the
output file based on a hash of the output file's content. But for very large output files, the hash can
slow down the link. Using a hash based UUID is important for reproducible builds, but if you are just doing
rapid debug builds, using -random_uuid may improve turn around time.
-root_safe
Sets the MH_ROOT_SAFE bit in the mach header of the output file.
-setuid_safe
Sets the MH_SETUID_SAFE bit in the mach header of the output file.
-interposable
Indirects access to all to exported symbols when creating a dynamic library.
-init symbol_name
The specified symbol_name will be run as the first initializer. Only used when creating a dynamic
library.
-sub_library library_name
The specified dylib will be re-exported. For example the library_name for /usr/lib/libobjc_profile.A.dylib
would be libobjc. Only used when creating a dynamic library.
-sub_umbrella framework_name
The specified framework will be re-exported. Only used when creating a dynamic library.
-allowable_client name
Restricts what can link against the dynamic library being created. By default any code can link against
any dylib. But if a dylib is supposed to be private to a small set of clients, you can formalize that by
adding a -allowable_client for each client. If a client is libfoo.1.dylib its -allowable_client name would
be "foo". If a client is Foo.framework its -allowable_client name would be "Foo". For the degenerate case
where you want no one to ever link against a dylib, you can set the -allowable_client to "!".
-client_name name
Enables a bundle to link against a dylib that was built with -allowable_client. The name specified must
match one of the -allowable_client names specified when the dylib was created.
-umbrella framework_name
Specifies that the dylib being linked is re-exported through an umbrella framework of the specified name.
-headerpad size
Specifies the minimum space for future expansion of the load commands. Only useful if intend to run
install_name_tool to alter the load commands later. Size is a hexadecimal number.
-headerpad_max_install_names
Automatically adds space for future expansion of load commands such that all paths could expand to
MAXPATHLEN. Only useful if intend to run install_name_tool to alter the load commands later.
-bind_at_load
Sets a bit in the mach header of the resulting binary which tells dyld to bind all symbols when the binary
is loaded, rather than lazily.
-force_flat_namespace
Sets a bit in the mach header of the resulting binary which tells dyld to not only use flat namespace for
the binary, but force flat namespace binding on all dylibs and bundles loaded in the process. Can only be
used when linking main executables.
-sectalign segname sectname value
The section named sectname in the segment segname will have its alignment set to value, where value is a
hexadecimal number that must be an integral power of 2.
-stack_addr address
Specifies the initial address of the stack pointer value, where value is a hexadecimal number rounded to a
page boundary.
-segprot segname max_prot init_prot
Specifies the maximum and initial virtual memory protection of the named segment, name, to be max and init
,respectively. The values for max and init are any combination of the characters `r' (for read), `w' (for
write), `x' (for execute) and `-' (no access). Except for x86_64 architecture, max_prot will always be set
to the same value as init_prot.
-seg_addr_table filename
Specifies a file containing base addresses for dynamic libraries. Each line of the file is a hexadecimal
base address followed by whitespace then the install name of the corresponding dylib. The # character
denotes a comment.
-segs_read_write_addr address
Allows a dynamic library to be built where the read-only and read-write segments are not contiguous. The
address specified is a hexadecimal number that indicates the base address for the read-write segments.
-segs_read_only_addr address
Allows a dynamic library to be built where the read-only and read-write segments are not contiguous. The
address specified is a hexadecimal number that indicates the base address for the read-only segments.
-segaddr name address
Specifies the starting address of the segment named name to be address. The address must be a hexadecimal
number that is a multiple of 4K page size.
-seg_page_size name size
Specifies the page size used by the specified segment. By default the page size is 4096 for all segments.
The linker will lay out segments such that size of a segment is always an even multiple of its page size.
-dylib_file install_name:file_name
Specifies that a dynamic shared library is in a different location than its standard location. Use this
option when you link with a library that is dependent on a dynamic library, and the dynamic library is in a
location other than its default location. install_name specifies the path where the library normally
resides. file_name specifies the path of the library you want to use instead. For example, if you link to a
library that depends upon the dynamic library libsys and you have libsys installed in a nondefault
location, you would use this option: -dylib_file /lib/libsys_s.A.dylib:/me/lib/libsys_s.A.dylib.
-prebind
The created output file will be in the prebound format. This was used in Mac OS X 10.3 and earlier to
improve launch performance.
-weak_reference_mismatches treatment
Specifies what to do if a symbol is weak-imported in one object file but not weak-imported in another. The
valid treatments are: error, weak, or non-weak. The default is non-weak.
-deployment_target_mismatches treatment
Specifies what to do if linking an object file with a deployment target lower than the target specified
using -platform_version. The valid treatments are: error, warning, suppress. The default is warning.
-read_only_relocs treatment
Enables the use of relocations in read-only segments. Options are: 'warning', 'error', or 'suppress'. The
default and only supported option for dynamic binaries is 'error'. Other treatments are reserved for use
with firmware or embedded targets.
-force_cpusubtype_ALL
The is only applicable with -arch ppc. It tells the linker to ignore the PowerPC cpu requirements (e.g.
G3, G4 or G5) encoded in the object files and mark the resulting binary as runnable on any PowerPC cpu.
-dylinker_install_name path
Only used when building dyld.
-no_arch_warnings
Suppresses warning messages about files that have the wrong architecture for the -arch flag
-arch_errors_fatal
Turns into errors, warnings about files that have the wrong architecture for the -arch flag.
-e symbol_name
Specifies the entry point of a main executable. By default the entry name is "start" which is found in
crt1.o which contains the glue code need to set up and call main().
-w Suppress all warning messages
-final_output name
Specifies the install name of a dylib if -install_name is not used. This option is used by compiler driver
when it is invoked with multiple -arch arguments.
-arch_multiple
Specifies that the linker should augment error and warning messages with the architecture name. This
option is used by compiler driver when it is invoked with multiple -arch arguments.
-twolevel_namespace_hints
Specifies that hints should be added to the resulting binary that can help speed up runtime binding by dyld
as long as the libraries being linked against have not changed.
-dot path
Create a file at the specified path containing a graph of symbol dependencies. The .dot file can be viewed
in GraphViz.
-keep_relocs
Add section based relocation records to a final linked image. These relocations are ignored at runtime by
dyld.
-warn_stabs
Print a warning when the linker cannot do a BINCL/EINCL optimization because the compiler put a bad stab
symbol inside a BINCL/EINCL range.
-warn_commons
Print a warning whenever a tentative definition in an object file is found and a external symbol by the
same name is also found in a linked dylib. This often means that the extern keyword is missing from a
variable declaration in a header file.
-read_only_stubs
[i386 only] Makes the __IMPORT segment of a final linked images read-only. This option makes a program
slightly more secure in that the JMP instructions in the i386 fast stubs cannot be easily overwritten by
malicious code. The downside is the dyld must use mprotect() to temporarily make the segment writable
while it is binding the stubs.
-slow_stubs
[i386 only] Instead of using single JMP instruction stubs, the linker creates code in the __TEXT segment
which calls through a lazy pointer in the __DATA segment.
-interposable_list filename
The specified filename contains a list of global symbol names that should always be accessed indirectly.
For instance, if libSystem.dylib is linked such that _malloc is interposable, then calls to malloc() from
within libSystem will go through a dyld stub and could potentially indirected to an alternate malloc. If
libSystem.dylib were built without making _malloc interposable then if _malloc was interposed at runtime,
calls to malloc from with libSystem would be missed (not interposed) because they would be direct calls.
-no_function_starts
By default the linker creates a compress table of function start addresses in the LINKEDIT of final linked
image. This option disables that behavior.
-no_objc_category_merging
By default when producing final linked image, the linker will optimize Objective-C classes by merging any
categories on a class into the class. Both the class and its categories must be defined in the image being
linked for the optimization to occur. Using this option disables that behavior.
-objc_relative_method_lists
By default when producing final linked image, if targeting a new enough OS version, the linker will rewrite
ObjC method lists from the tradition three pointers to use three read-only delta pointers. This option
allows you to force the use of relative method lists even though the OS version is too low.
-no_objc_relative_method_lists
By default when producing final linked image, if targeting a new enough OS version, the linker will rewrite
ObjC method lists from the tradition three pointers to use three read-only delta pointers. This option
allows you to force the use of traditional three pointer method lists.
-object_path_lto filename
When performing Link Time Optimization (LTO) and a temporary mach-o object file is needed, if this option
is used, the temporary file will be stored at the specified path and remain after the link is complete.
Without the option, the linker picks a path and deletes the object file before the linker tool completes,
thus tools such as the debugger or dsymutil will not be able to access the DWARF debug info in the
temporary object file.
-lto_library path
When performing Link Time Optimization (LTO), the linker normally loads libLTO.dylib relative to the linker
binary (../lib/libLTO.dylib). This option allows the user to specify the path to a specific libLTO.dylib to
load instead.
-cache_path_lto path
When performing Incremental Link Time Optimization (LTO), use this directory as a cache for incremental
rebuild.
-prune_interval_lto seconds
When performing Incremental Link Time Optimization (LTO), the cache will pruned after the specified
interval. A value 0 will force pruning to occur and a value of -1 will disable pruning.
-prune_after_lto seconds
When pruning the cache for Incremental Link Time Optimization (LTO), the cache entries are removed after
the specified interval.
-max_relative_cache_size_lto percent
When performing Incremental Link Time Optimization (LTO), the cache will be pruned to not go over this
percentage of the free space. I.e. a value of 100 would indicate that the cache may fill the disk, and a
value of 50 would indicate that the cache size will be kept under the free disk space.
-fixup_chains_section
For use with -static or -preload when -pie is used. Tells the linker to add a __TEXT,__chain_starts section
which starts with a dyld_chained_starts_offsets struct which specifies the pointer format and the file
offsets to the start of every fixup chain. The rebase targets in the chains are vm offsets.
-fixup_chains_section_vm
Same as -fixup_chains_section, but fixes a bug. The offsets in the __chain_starts section are vm offsets
from the __TEXT segment, and the rebase targets in the chains are vm offsets.
-page_align_data_atoms
During development, this option can be used to space out all global variables so each is on a separate
page. This is useful when analyzing dirty and resident pages. The information can then be used to create
an order file to cluster commonly used/dirty globals onto the same page(s).
-not_for_dyld_shared_cache
Normally, the linker will add extra info to dylibs with -install_name starting with /usr/lib or
/System/Library/ that allows the dylib to be placed into the dyld shared cache. Adding this option tells
the linker to not add that extra info.
-no_dynamic_access
Marks the output file so that dyld will not (directly) allow it to be dlopen()ed and dyld will not find any
symbols in it with dlsym().
-search_in_sparse_frameworks
For use when linking against versioned frameworks that do not have a normal variant. By default when
-framework Foo,_suffix is used, the linker will follow Foo.framework/Foo if it is a symbolic link, append
_suffix and search for a file with that path. When this option is used, the linker will also search for
Foo.framework/Versions/Current/Foo_suffix.
-ld_classic
Override the choice of linker, and force the use of ld-classic to link the binary. This is incompatible
with options such as -merge*, used to build/merge libraries.
-ld_new
Override the choice of linker, and force the use of ld to link the binary. This is incompatible with older
architectures such as armv7k and i386.
Mergeable Library Options
-make_mergeable
Adds additional metadata to a dylib which makes it a mergeable library. It can still be used as a dylib,
or can be merged into other binaries when they link it with a -merge* option.
-merge-lx
This is the same as the -lx option but means to merge the contents of the library x into this binary.
-merge_library path_to_library
This is the same as listing a file name path to a library on the link line but also merges the contents of
the library into this binary.
-merge_framework name[,suffix]
This is the same as the -framework name[,suffix] but means that the contents of the framework should be
merged into this binary.
-no_merged_libraries_hook
When using mergeable libraries ld automatically adds a hook to redirect bundle resource lookups from
mergeable frameworks into the merged binary. Use this option to disable the hook.
The hook requires a minimum deployment version of iOS 12, you can use the option to disable the hook with a
lower deployment target if your frameworks don't require bundle resource lookups. Disabling the hook might
also improve launch time performance, so it's good to disable it regardless of the deployment target if
it's not required.
-add_mergeable_debug_hook
Use this option in debug builds of mergeable libraries to add a hook to redirect bundle resource lookups
based on private/internal classes.
Obsolete Options
-segalign value
All segments must be page aligned.
-seglinkedit
Object files (MH_OBJECT) with a LINKEDIT segment are no longer supported. This option is obsolete.
-noseglinkedit
This is the default. This option is obsolete.
-fvmlib
Fixed VM shared libraries (MH_FVMLIB) are no longer supported. This option is obsolete.
-sectobjectsymbols segname sectname
Adding a local label at a section start is no longer supported. This option is obsolete.
-nofixprebinding
The MH_NOFIXPREBINDING bit of mach_headers has been ignored since Mac OS X 10.3.9. This option is
obsolete.
-noprebind_all_twolevel_modules
Multi-modules in dynamic libraries have been ignored at runtime since Mac OS X 10.4.0. This option is
obsolete.
-prebind_all_twolevel_modules
Multi-modules in dynamic libraries have been ignored at runtime since Mac OS X 10.4.0. This option is
obsolete.
-prebind_allow_overlap
When using -prebind, the linker allows overlapping by default, so this option is obsolete.
-noprebind
LD_PREBIND is no longer supported as a way to force on prebinding, so there no longer needs to be a command
line way to override LD_PREBIND. This option is obsolete.
-sect_diff_relocs treatment
This option was an attempt to warn about linking .o files compiled without -mdynamic-no-pic into a main
executable, but the false positive rate generated too much noise to make the option useful. This option is
obsolete.
-run_init_lazily
This option was removed in Mac OS X 10.2.
-single_module
This is now the default so does not need to be specified.
-multi_module
Multi-modules in dynamic libraries have been ignored at runtime since Mac OS X 10.4.0. This option is
obsolete.
-no_dead_strip_inits_and_terms
The linker never dead strips initialization and termination routines. They are considered "roots" of the
dead strip graph.
-A basefile
Obsolete incremental load format. This option is obsolete.
-b Used with -A option to strip base file's symbols. This option is obsolete. Obsolete option to produce a
load map. Use -map option instead.
-Sn Don't strip any symbols. This is the default. This option is obsolete.
-Si Optimize stabs debug symbols to remove duplicates. This is the default. This option is obsolete.
-Sp Write minimal stabs which causes the debugger to open and read the original .o file for full stabs. This
style of debugging is obsolete in Mac OS X 10.5. This option is obsolete.
-X Strip local symbols that begin with 'L'. This is the default. This option is obsolete.
-s Completely strip the output, including removing the symbol table. This file format variant is no longer
supported. This option is obsolete.
-m Don't treat multiple definitions as an error. This is no longer supported. This option is obsolete.
-ysymbol
Display each file in which symbol is used. This was previously used to debug where an undefined symbol was
used, but the linker now automatically prints out all usages. The -why_live option can also be used to
display what kept a symbol from being dead stripped. This option is obsolete.
-Y number
Used to control how many occurrences of each symbol specified with -y would be shown. This option is
obsolete.
-nomultidefs
Only used when linking an umbrella framework. Sets the MH_NOMULTIDEFS bit in the mach_header. The
MH_NOMULTIDEFS bit has been obsolete since Mac OS X 10.4. This option is obsolete.
-multiply_defined_unused treatment
Previously provided a way to warn or error if any of the symbol definitions in the output file matched any
definitions in dynamic library being linked. This option is obsolete.
-multiply_defined treatment
Previously provided a way to warn or error if any of the symbols used from a dynamic library were also
available in another linked dynamic library. This option is obsolete.
-private_bundle
Previously prevented errors when -flat_namespace, -bundle, and -bundle_loader were used and the bundle
contained a definition that conflicted with a symbol in the main executable. The linker no longer errors
on such conflicts. This option is obsolete.
-noall_load
This is the default. This option is obsolete.
-seg_addr_table_filename path
Use path instead of the install name of the library for matching an entry in the seg_addr_table. This
option is obsolete.
-sectorder segname sectname orderfile
Replaced by more general -order_file option.
-sectorder_detail
Produced extra logging about which entries from a sectorder entries were used. Replaced by
-order_file_statistics. This option is obsolete.
-poison_symbol symbolName
Causes any use of the named symbol to be an error. Useful to make sure you are not using some API.
-poison_symbols_list filePath
The specified filePath contains a list of symbol names that are to be poisoned.
SEE ALSO
ld-classic(1), ld-layout-file(1), as(1), ar(1), cc(1), dyld_info(1), nm(1), otool(1) lipo(1), arch(3), dyld(3),
Mach-O(5), strip(1), rebase(1)
Darwin June 21, 2023 Darwin
DYLD(1)
DYLD(1) General Commands Manual DYLD(1)
NAME
dyld - the dynamic linker
SYNOPSIS
DYLD_FRAMEWORK_PATH
DYLD_FALLBACK_FRAMEWORK_PATH
DYLD_VERSIONED_FRAMEWORK_PATH
DYLD_LIBRARY_PATH
DYLD_FALLBACK_LIBRARY_PATH
DYLD_VERSIONED_LIBRARY_PATH
DYLD_IMAGE_SUFFIX
DYLD_INSERT_LIBRARIES
DYLD_PRINT_TO_FILE
DYLD_PRINT_LIBRARIES
DYLD_PRINT_LOADERS
DYLD_PRINT_SEARCHING
DYLD_PRINT_APIS
DYLD_PRINT_BINDINGS
DYLD_PRINT_INITIALIZERS
DYLD_PRINT_SEGMENTS
DYLD_PRINT_ENV
DYLD_PRINT_LINKS_WITH
DYLD_SHARED_REGION
DYLD_SHARED_CACHE_DIR
DESCRIPTION
The dynamic linker (dyld) checks the following environment variables during the launch of each process.
Note: If System Integrity Protection is enabled, these environment variables are ignored when executing binaries
protected by System Integrity Protection.
DYLD_FRAMEWORK_PATH
This is a colon separated list of directories that contain frameworks. The dynamic linker searches these
directories before it searches for the framework by its install name. It allows you to test new versions
of existing frameworks. (A framework is a library install name that ends in the form
XXX.framework/Versions/A/XXX or XXX.framework/XXX, where XXX and A are any name.)
For each framework that a program uses, the dynamic linker looks for the framework in each directory in
DYLD_FRAMEWORK_PATH in turn. If it looks in all those directories and can't find the framework, it uses
whatever it would have loaded if DYLD_FRAMEWORK_PATH had not been set.
Use the -L option to otool(1) to discover the frameworks and shared libraries that the executable is
linked against.
DYLD_FALLBACK_FRAMEWORK_PATH
This is a colon separated list of directories that contain frameworks. If a framework is not found at its
install path, dyld uses this as a list of directories to search for the framework.
For new binaries (Fall 2023 or later) there is no default fallback. For older binaries, there is a
default fallback search path of: /Library/Frameworks:/System/Library/Frameworks
DYLD_VERSIONED_FRAMEWORK_PATH
This is a colon separated list of directories that contain potential override frameworks. The dynamic
linker searches these directories for frameworks. For each framework found dyld looks at its LC_ID_DYLIB
and gets the current_version and install name. Dyld then looks for the framework at the install name
path. Whichever has the larger current_version value will be used in the process whenever a framework
with that install name is required. This is similar to DYLD_FRAMEWORK_PATH except instead of always
overriding, it only overrides if the supplied framework is newer. Note: dyld does not check the
framework's Info.plist to find its version. Dyld only checks the -current_version number supplied when
the framework was created.
DYLD_LIBRARY_PATH
This is a colon separated list of directories that contain libraries. The dynamic linker searches these
directories before it searches the default locations for libraries. It allows you to test new versions of
existing libraries.
For each dylib that a program uses, the dynamic linker looks for its leaf name in each directory in
DYLD_LIBRARY_PATH.
Use the -L option to otool(1) to discover the frameworks and shared libraries that the executable is
linked against.
DYLD_FALLBACK_LIBRARY_PATH
This is a colon separated list of directories that contain libraries. If a dylib is not found at its
install path, dyld uses this as a list of directories to search for the dylib.
For new binaries (Fall 2023 or later) there is no default. For older binaries, there is a default
fallback search path of: /usr/local/lib:/usr/lib.
DYLD_VERSIONED_LIBRARY_PATH
This is a colon separated list of directories that contain potential override libraries. The dynamic
linker searches these directories for dynamic libraries. For each library found dyld looks at its
LC_ID_DYLIB and gets the current_version and install name. Dyld then looks for the library at the install
name path. Whichever has the larger current_version value will be used in the process whenever a dylib
with that install name is required. This is similar to DYLD_LIBRARY_PATH except instead of always
overriding, it only overrides is the supplied library is newer.
DYLD_IMAGE_SUFFIX
This is set to a string of a suffix to try to be used for all shared libraries used by the program. For
libraries ending in ".dylib" the suffix is applied just before the ".dylib". For all other libraries the
suffix is appended to the library name. This is useful for using conventional "_profile" and "_debug"
libraries and frameworks.
DYLD_INSERT_LIBRARIES
This is a colon separated list of additional dynamic libraries to load before the ones specified in the
program. If instead, your goal is to substitute a library that would normally be loaded, use
DYLD_LIBRARY_PATH or DYLD_FRAMEWORK_PATH instead.
DYLD_PRINT_TO_FILE
This is a path to a (writable) file. Normally, the dynamic linker writes all logging output (triggered by
DYLD_PRINT_* settings) to file descriptor 2 (which is usually stderr). But this setting causes the
dynamic linker to write logging output to the specified file.
DYLD_PRINT_ENV
If set, causes dyld to print a line of key=value for each environment variable in the process.
DYLD_PRINT_LIBRARIES
If set, causes dyld to print a line for each mach-o image loaded into a process. This is useful to make
sure that the use of DYLD_LIBRARY_PATH is getting what you want.
DYLD_PRINT_LOADERS
If set, causes dyld to print a line whether each image is tracked by a JustInTimeLoader or a
PrebuiltLoader. Additionally, it prints if a PrebuiltLoaderSet was used to launch the process or if a
PrebuiltLoader was written to make the next launch faster.
DYLD_PRINT_SEARCHING
If set, causes dyld to print a line about each file system path checked when searching for an image to
load.
DYLD_PRINT_INITIALIZERS
If set, causes dyld to print out a line when running each initializer in every image. Initializers run by
dyld include constructors for C++ statically allocated objects, functions marked with
__attribute__((constructor)), and -init functions.
DYLD_PRINT_APIS
If set, causes dyld to print a line whenever a dyld API is called (e.g. dlopen()).
DYLD_PRINT_SEGMENTS
If set, causes dyld to print out a line containing the name and address range of each mach-o segment that
dyld maps. In addition it prints information about if the image was from the dyld shared cache.
DYLD_PRINT_BINDINGS
If set, causes dyld to print a line each time a symbolic name is bound.
DYLD_PRINT_LINKS_WITH
If set to the leaf name of a mach-o image, dyld prints why that image was loaded, including the chain of
links from the main executable or dlopen()ed image to the request image name. The leaf name needs to be
the actual leaf file/install name (e.g. "libz.1.dylib" and not one of the aliases such as "libz.dylib").
When reporting the chain of links the --> may contain a letter (-w-> is a weak link, -r-> is a re-export,
-u-> is an upward link, -d-> is a delay-init link).
DYLD_SHARED_REGION
This can be "use" (the default) or "private". Setting it to "private" tells dyld to remove the shared
region from the process address space and mmap() back in a private copy of the dyld shared cache in the
shared region address range. This is only useful if the shared cache on disk has been updated and is
different than the shared cache in use.
DYLD_SHARED_CACHE_DIR
This is a directory containing dyld shared cache files. This variable can be used in conjunction with
DYLD_SHARED_REGION=private to run a process with an alternate shared cache.
DYNAMIC LIBRARY LOADING
Unlike many other operating systems, Darwin does not locate dependent dynamic libraries via their leaf file name.
Instead the full path to each dylib is used (e.g. /usr/lib/libSystem.B.dylib). But there are times when a full
path is not appropriate; for instance, may want your binaries to be installable in anywhere on the disk. To
support that, there are three @xxx/ variables that can be used as a path prefix. At runtime dyld substitutes a
dynamically generated path for the @xxx/ prefix.
@executable_path/
This variable is replaced with the path to the directory containing the main executable for the process.
This is useful for loading dylibs/frameworks embedded in a .app directory. If the main executable file is
at /some/path/My.app/Contents/MacOS/My and a framework dylib file is at
/some/path/My.app/Contents/Frameworks/Foo.framework/Versions/A/Foo, then the framework load path could be
encoded as @executable_path/../Frameworks/Foo.framework/Versions/A/Foo and the .app directory could be
moved around in the file system and dyld will still be able to load the embedded framework.
@loader_path/
This variable is replaced with the path to the directory containing the mach-o binary which contains the
load command using @loader_path. Thus, in every binary, @loader_path resolves to a different path, whereas
@executable_path always resolves to the same path. @loader_path is useful as the load path for a
framework/dylib embedded in a plug-in, if the final file system location of the plugin-in unknown (so
absolute paths cannot be used) or if the plug-in is used by multiple applications (so @executable_path
cannot be used). If the plug-in mach-o file is at /some/path/Myfilter.plugin/Contents/MacOS/Myfilter and a
framework dylib file is at /some/path/Myfilter.plugin/Contents/Frameworks/Foo.framework/Versions/A/Foo,
then the framework load path could be encoded as @loader_path/../Frameworks/Foo.framework/Versions/A/Foo
and the Myfilter.plugin directory could be moved around in the file system and dyld will still be able to
load the embedded framework.
@rpath/
Dyld maintains a current stack of paths called the run path list. When @rpath is encountered it is
substituted with each path in the run path list until a loadable dylib if found. The run path stack is
built from the LC_RPATH load commands in the dependency chain that lead to the current dylib load. You
can add an LC_RPATH load command to an image with the -rpath option to ld(1). You can even add a LC_RPATH
load command path that starts with @loader_path/, and it will push a path on the run path stack that
relative to the image containing the LC_RPATH. The use of @rpath is most useful when you have a complex
directory structure of programs and dylibs which can be installed anywhere, but keep their relative
positions. This scenario could be implemented using @loader_path, but every client of a dylib could need
a different load path because its relative position in the file system is different. The use of @rpath
introduces a level of indirection that simplifies things. You pick a location in your directory structure
as an anchor point. Each dylib then gets an install path that starts with @rpath and is the path to the
dylib relative to the anchor point. Each main executable is linked with -rpath @loader_path/zzz, where zzz
is the path from the executable to the anchor point. At runtime dyld sets it run path to be the anchor
point, then each dylib is found relative to the anchor point.
SEE ALSO
dyld_info(1), ld(1), otool(1)
Apple Inc. June 1, 2020 DYLD(1)
/usr/include/mach-o/loader.h
/* Constants for the cmd field of all load commands, the type */
#define LC_SEGMENT 0x1 /* segment of this file to be mapped */
#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */
#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */
#define LC_THREAD 0x4 /* thread */
#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */
#define LC_LOADFVMLIB 0x6 /* load a specified fixed VM shared library */
#define LC_IDFVMLIB 0x7 /* fixed VM shared library identification */
#define LC_IDENT 0x8 /* object identification info (obsolete) */
#define LC_FVMFILE 0x9 /* fixed VM file inclusion (internal use) */
#define LC_PREPAGE 0xa /* prepage command (internal use) */
#define LC_DYSYMTAB 0xb /* dynamic link-edit symbol table info */
#define LC_LOAD_DYLIB 0xc /* load a dynamically linked shared library */
#define LC_ID_DYLIB 0xd /* dynamically linked shared lib ident */
#define LC_LOAD_DYLINKER 0xe /* load a dynamic linker */
#define LC_ID_DYLINKER 0xf /* dynamic linker identification */
#define LC_PREBOUND_DYLIB 0x10 /* modules prebound for a dynamically */
/* linked shared library */
#define LC_ROUTINES 0x11 /* image routines */
#define LC_SUB_FRAMEWORK 0x12 /* sub framework */
#define LC_SUB_UMBRELLA 0x13 /* sub umbrella */
#define LC_SUB_CLIENT 0x14 /* sub client */
#define LC_SUB_LIBRARY 0x15 /* sub library */
#define LC_TWOLEVEL_HINTS 0x16 /* two-level namespace lookup hints */
#define LC_PREBIND_CKSUM 0x17 /* prebind checksum */
/*
* load a dynamically linked shared library that is allowed to be missing
* (all symbols are weak imported).
*/
#define LC_LOAD_WEAK_DYLIB (0x18 | LC_REQ_DYLD)
#define LC_SEGMENT_64 0x19 /* 64-bit segment of this file to be
mapped */
#define LC_ROUTINES_64 0x1a /* 64-bit image routines */
#define LC_UUID 0x1b /* the uuid */
#define LC_RPATH (0x1c | LC_REQ_DYLD) /* runpath additions */
#define LC_CODE_SIGNATURE 0x1d /* local of code signature */
#define LC_SEGMENT_SPLIT_INFO 0x1e /* local of info to split segments */
#define LC_REEXPORT_DYLIB (0x1f | LC_REQ_DYLD) /* load and re-export dylib */
#define LC_LAZY_LOAD_DYLIB 0x20 /* delay load of dylib until first use */
#define LC_ENCRYPTION_INFO 0x21 /* encrypted segment information */
#define LC_DYLD_INFO 0x22 /* compressed dyld information */
#define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */
#define LC_LOAD_UPWARD_DYLIB (0x23 | LC_REQ_DYLD) /* load upward dylib */
#define LC_VERSION_MIN_MACOSX 0x24 /* build for MacOSX min OS version */
#define LC_VERSION_MIN_IPHONEOS 0x25 /* build for iPhoneOS min OS version */
#define LC_FUNCTION_STARTS 0x26 /* compressed table of function start addresses */
#define LC_DYLD_ENVIRONMENT 0x27 /* string for dyld to treat
like environment variable */
#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */
#define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */
#define LC_SOURCE_VERSION 0x2A /* source version used to build binary */
#define LC_DYLIB_CODE_SIGN_DRS 0x2B /* Code signing DRs copied from linked dylibs */
#define LC_ENCRYPTION_INFO_64 0x2C /* 64-bit encrypted segment information */
#define LC_LINKER_OPTION 0x2D /* linker options in MH_OBJECT files */
#define LC_LINKER_OPTIMIZATION_HINT 0x2E /* optimization hints in MH_OBJECT files */
#define LC_VERSION_MIN_TVOS 0x2F /* build for AppleTV min OS version */
#define LC_VERSION_MIN_WATCHOS 0x30 /* build for Watch min OS version */
#define LC_NOTE 0x31 /* arbitrary data included within a Mach-O file */
#define LC_BUILD_VERSION 0x32 /* build for platform min OS version */
#define LC_DYLD_EXPORTS_TRIE (0x33 | LC_REQ_DYLD) /* used with linkedit_data_command, payload is trie */
#define LC_DYLD_CHAINED_FIXUPS (0x34 | LC_REQ_DYLD) /* used with linkedit_data_command */
#define LC_FILESET_ENTRY (0x35 | LC_REQ_DYLD) /* used with fileset_entry_command */
#define LC_ATOM_INFO 0x36 /* used with linkedit_data_command */
#define LC_FUNCTION_VARIANTS 0x37 /* used with linkedit_data_command */
#define LC_FUNCTION_VARIANT_FIXUPS 0x38 /* used with linkedit_data_command */
#define LC_TARGET_TRIPLE 0x39 /* target triple used to compile */
#define LC_LAZY_LOAD_DYLIB_INFO 0x3A /* used with linkedit_data_command */

浙公网安备 33010602011771号