1.6 Multilib and multiarch: several ABIs under one triple

GCC 15.2.0. To run the commands: an installed x86-64 compiler, and a bare-metal ARM cross compiler for the Cortex-M4 example.

You pass -m32, with no extra -L and no other flag. The link still picks up a 32-bit libgcc.a and a 32-bit libc.so, out of an installation whose default is 64-bit.

On a bare-metal toolchain you pass -mcpu=cortex-m4 -mfloat-abi=hard, and the same mechanism fails. The link succeeds, and the binary is built against the wrong float ABI.

One target triple can have several mutually incompatible ABIs. Multilib is how one toolchain ships a separate copy of every target library for each of them, and each copy is called a variant. The driver tries every search prefix up to four ways, adding the variant's directory names, and then walks the prefixes once more with no variant. That last walk is why the Cortex-M4 link succeeds instead of failing. Multiarch, Debian's layout of one library directory per triple, is a separate scheme that shares the same search code.

This chapter assumes Chapter 1.2, for the sysroot and add_sysrooted_prefix, Chapter 1.3, for spec text and its if/else form, and Chapter 1.5, for the prefix lists that the driver searches and the add_prefix calls that build them.

MULTILIB_OPTIONS: one library build per option combination

MULTILIB_OPTIONS lists the options that select a variant, and the build compiles the target libraries once for each combination of them that can be used together. The driver then has to pick the matching set of libraries on every invocation, and the -m32 and Cortex-M4 links both depend on that choice. The internals manual documents the variable under Target Makefile Fragments:

Write options that are mutually incompatible side by side, separated by a slash. Write options that may be used together separated by a space. The build procedure will build all combinations of compatible options.

For example, if you set MULTILIB_OPTIONS to m68000/m68020 msoft-float, Makefile will build special versions of libgcc.a using the following sets of options: -m68000, -m68020, -msoft-float, -m68000 -msoft-float, and -m68020 -msoft-float.

— gcc/doc/fragments.texi:63-83

One variable setting gives five variants of libgcc.a, and the other target libraries multiply the same way. libstdc++, libatomic, newlib's libc.a and every crt*.o are each built and installed once per variant.

Checking the variants with -print-multi-lib and -print-multi-directory

-print-multi-lib lists every variant that a toolchain has, while -print-multi-directory names the one variant that a set of options selects. A wrong-library link raises both questions, and two more: the name of the variant's directory under OS conventions, and the file that the search found. Each of these commands answers one question, as its comment says:

$ gcc -print-multi-lib                  # every variant this toolchain HAS
$ gcc -m32 -print-multi-directory       # GCC-side dir for THIS invocation
$ gcc -m32 -print-multi-os-directory    # OS-side dir for THIS invocation
$ gcc -m32 -print-file-name=libgcc.a    # which variant actually won

-print-multi-lib prints one line per variant, in the format that its manual entry gives: the directory name, a ;, then the switches that select the variant. Each switch has @ in place of -, and there are no spaces between the switches. For a toolchain with 32-bit and x32 variants, the output is shaped like this:

.;
32;@m32
x32;@mx32

print_multilib_info prints these lines from the driver's table of variants, multilib_select (gcc/gcc.cc:10042). The table has a format of its own, in which a directory may carry a multiarch name after a : (gcc/gcc.cc:9750-9761). The printed lines stop at the :.

If the variant you want is missing from -print-multi-lib, the library was never built, and no -B or --sysroot can make the driver find it. You need a toolchain built with that variant, or you need to build one. Make this check first, because it is faster than reasoning about paths. A short list usually means that GCC was configured with --disable-multilib, which gcc -v shows. The install manual documents that option under Configuration.

-print-multi-directory and -print-multi-os-directory print the directory of the selected variant, or . when there is no variant (gcc/gcc.cc:8858-8865, :8888-8895). The GCC manual documents every -print-* option in this chapter under Developer Options.

multilib_dir and multilib_os_dir: one variant, two directory names

Each variant has two directory names: multilib_dir inside GCC's own install tree, and multilib_os_dir inside the sysroot and other directories that follow OS convention. Most of the confusion about multilibs comes from this split. lib/gcc/<t>/<v>/32/ and <sysroot>/usr/lib32/ hold the same variant, so a search by hand for a missing library has to look in both:

GCC-sideOS-side
Applies todirectories inside GCC's install, such as lib/gcc/<t>/<v>/<dir>/directories that follow OS convention, such as the sysroot's /lib and /usr/lib
Typical value32../lib32
Fragment variableMULTILIB_DIRNAMESMULTILIB_OSDIRNAMES
Driver variablemultilib_dirmultilib_os_dir
Print with-print-multi-directory-print-multi-os-directory

The driver holds the two names, and a third for multiarch, in three variables. The comment on each says that set_multilib_dir sets it from the compilation options:

/* Subdirectory to use for locating libraries.  Set by
   set_multilib_dir based on the compilation options.  */

static const char *multilib_dir;

/* Subdirectory to use for locating libraries in OS conventions.  Set by
   set_multilib_dir based on the compilation options.  */

static const char *multilib_os_dir;

/* Subdirectory to use for locating libraries in multiarch conventions.  Set by
   set_multilib_dir based on the compilation options.  */

static const char *multiarch_dir;

Listing 1.6-1: the three subdirectory variables (gcc/gcc.cc:1666-1679).

There are two names, three with multiarch, because GCC and the distribution each own a directory layout. GCC owns its own tree, so it may name its variants however it likes. Whoever built the distribution decides the sysroot's layout: /usr/lib32 on one, Debian's /usr/lib/i386-linux-gnu on another, /usr/lib64 on a third. The target's build configuration maps GCC's convention onto the OS's.

set_multilib_dir chooses all three names once per invocation, by matching the command-line switches against the table of variants (gcc/gcc.cc:9764). The table is itself a spec, named multilib, and is stored as a string in the spec table like any other (gcc.cc:1733). The driver builds that string at run time, because it can be too long for some compilers' string limits (gcc.cc:1326-1330).

Spec text reads the OS-side name through %M, one of the directives from Chapter 1.3 that read driver state. It expands to multilib_os_dir, or to . when there is no variant:

	  case 'M':
	    if (multilib_os_dir == NULL)
	      obstack_1grow (&obstack, '.');
	    else
	      obstack_grow (&obstack, multilib_os_dir,
			    strlen (multilib_os_dir));

Listing 1.6-2: %M, the OS-side directory in spec text (gcc/gcc.cc:6805-6811).

for_each_path: the four ways each prefix is tried

for_each_path tries every prefix on a search list up to four ways, in a fixed order, and it is where the variant's directory names enter the search. Each attempt is a block with its own comment inside the function (gcc/gcc.cc:2778). Watch the fourth, because it is where multilib_dir and multilib_os_dir part ways.

	  /* Look first in MACHINE/VERSION subdirectory.  */
	  if (!skip_multi_dir)
	    {
	      memcpy (path + len, multi_suffix, suffix_len + 1);

Listing 1.6-3: attempt one, machine and version plus multilib_dir (gcc/gcc.cc:2838-2841).

	  /* Some paths are tried with just the machine (ie. target)
	     subdir.  This is used for finding as, ld, etc.  */
	  if (!skip_multi_dir
	      && pl->require_machine_suffix == 2)

Listing 1.6-4: attempt two, the machine name only (gcc/gcc.cc:2847-2850).

	  /* Now try the multiarch path.  */
	  if (!skip_multi_dir
	      && !pl->require_machine_suffix && multiarch_dir)

Listing 1.6-5: attempt three, multiarch (gcc/gcc.cc:2858-2860).

	  /* Now try the base path.  */
	  if (!pl->require_machine_suffix
	      && !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
	    {
	      const char *this_multi;
	      ...
	      if (pl->os_multilib)
		{
		  this_multi = multi_os_dir;

Listing 1.6-6: attempt four, the bare prefix plus multilib_os_dir (gcc/gcc.cc:2868-2884).

In Listing 1.6-6, a per-prefix flag, pl->os_multilib, chooses between multi_os_dir and multi_dir. The flag is the last argument to add_prefix, and Listing 1.5-6 in Chapter 1.5 registers the tool directory with a final argument of 1. That argument marks the tool directory as an OS-convention prefix, so the driver appends ../lib32 to it rather than 32. A 32-bit variant therefore expands differently on the two kinds of prefix:

$prefix/lib/gcc/<target>/<ver>/32/     ← multilib_dir, on a GCC-convention prefix
<sysroot>/usr/lib/../lib32/            ← multilib_os_dir, on an OS-convention prefix

The driver does not normalise .. away, so /usr/lib/../lib32/ is the real shape of the path. That is why -print-multi-os-directory prints values such as ../lib32, and why an strace of a link shows paths that look wrong but are correct.

Attempt two, require_machine_suffix == 2 in Listing 1.6-4, adds the machine name only, and the driver uses it to find as and ld. It is how a toolchain finds $prefix/<target>/bin/as with no version component, and it applies to exec_prefixes, not to libraries.

The fallback pass is a second walk over the whole prefix list in for_each_path, this time with no variant directories. It is why a link can succeed against the wrong ABI, as the Cortex-M4 link does. Listing 1.6-7 starts the second walk, and its comment says that it skips the directories already tried:

      /* Run through the paths again, this time without multilibs.
	 Don't repeat any we have already seen.  */
      if (multi_dir)
	{
	  free (CONST_CAST (char *, multi_dir));
	  multi_dir = NULL;
	  ...
	}
      else
	skip_multi_dir = true;

Listing 1.6-7: the second pass (gcc/gcc.cc:2902-2914).

GCC makes the second walk on purpose, so that a target can ship only the default variant of a library rather than every combination. That matters on ARM, where the -mcpu and float-ABI axes multiply into an enormous number of combinations.

A wrong-ABI link happens when the variant directory holds no copy of a library. The search then falls through to the default directory, and ld receives an archive that it reads without complaint. Sometimes the link prints a diagnostic about incompatible attributes, but on many targets it prints none.

The internals manual documents both walks, and a ! that turns the second one off. A target for which falling through is worse than failing puts the ! at the start of its MULTILIB_OSDIRNAMES entry:

If the osdir part begins with a !, GCC will not search in the non-multilib directory and use exclusively the multilib directory. Otherwise, the compiler will examine the search path for libraries and crt files twice; the first time it will add multilib to each directory in the search path, the second it will not.

— gcc/doc/fragments.texi:205-210

When a link may have fallen back, do not reason about directories. Ask the driver which file it found and which variant the options select:

$ gcc -mcpu=cortex-m4 -mfloat-abi=hard -print-file-name=libgcc.a
$ gcc -mcpu=cortex-m4 -mfloat-abi=hard -print-multi-directory

If the second command prints a variant directory and the first prints a path that does not contain it, the search fell through to the default variant.

-print-multiarch: per-triple directories, separate from multilib

-print-multiarch prints the multiarch directory name that the options select, such as x86_64-linux-gnu. Multiarch is Debian's scheme of one library directory per triple, so that several architectures' libraries can coexist in one filesystem. It is independent of multilib, because a configuration can use multiarch with no multilibs, but it shares the search code and has its own attempt in for_each_path (Listing 1.6-5).

$ gcc -print-multiarch          # e.g. x86_64-linux-gnu

When there is no multiarch directory, -print-multiarch prints an empty line, not the . that -print-multi-directory and -print-multi-os-directory print (gcc.cc:8867-8874). The difference matters when a script reads the output.

A variant can have both a multiarch directory and an OS multilib directory. The internals manual fixes the order in which the driver searches them:

Each multiarch subdirectory will be searched before the corresponding OS multilib directory, for example /lib/i386-linux-gnu before /lib/../lib32.

— gcc/doc/fragments.texi:218-220

SYSROOT_SUFFIX_SPEC: a different sysroot for each variant

SYSROOT_SUFFIX_SPEC lets a target give each variant a sysroot of its own, instead of subdirectories inside one sysroot. The two schemes behave differently under -print-sysroot, so it matters which one a target uses.

Subdirectories in one sysroot. The common scheme keeps every variant in a single sysroot and appends the OS-side directory to paths inside it. One /arm-rootfs then contains both usr/lib and usr/lib32.

One sysroot per variant. Some targets append a suffix to the sysroot itself, computed from the options by SYSROOT_SUFFIX_SPEC. gcc.cc declares that spec with an empty default (gcc.cc:1229, :1193-1195). The GCC manual documents that such a suffix exists, and --no-sysroot-suffix to turn it off, under Directory Options. MIPS is the canonical user:

#undef SYSROOT_SUFFIX_SPEC
#define SYSROOT_SUFFIX_SPEC						\
    "/%{mmicromips:micro}mips%{mel|EL:el}-" MIPS_SYSVERSION_SPEC	\
    "%{msoft-float:-soft;:-hard}"					\
    "%{!mips32r6:%{!mips64r6:%{mnan=2008:-nan2008}}}%{muclibc:-uclibc}"

Listing 1.6-8: MIPS computing a sysroot suffix from the variant options (gcc/config/mips/mti-linux.h:29-33).

Listing 1.6-8 is ordinary spec text, with the if/else form from Chapter 1.3, so --sysroot=/opt/rootfs -EL -msoft-float searches /opt/rootfs/mipsel-r2-soft/…. The driver evaluates the suffix once at startup (gcc.cc:8542-8552). It then appends the suffix inside add_sysrooted_prefix (gcc.cc:3194-3196), so that function, from Chapter 1.2, joins three pieces rather than two: the sysroot, the suffix and the prefix. On such a target the suffix has three consequences:

  • -print-sysroot prints the suffixed path. Its output changes with -EL or -msoft-float, so do not cache it. Chapter 1.14 reads the code, in Listing 1.14-2.

  • --with-sysroot gives only the base. The sysroot is not one root filesystem but a family of them. The suffix does not appear in the configure line, so gcc -v does not show it.

  • The startfile prefix varies too. The same target makes the startfile prefix multilib-conditional, through the STARTFILE_PREFIX_SPEC branch from Chapter 1.5:

    #undef STARTFILE_PREFIX_SPEC
    #define STARTFILE_PREFIX_SPEC                          \
      "%{mabi=32: /usr/local/lib/ /lib/ /usr/lib/}         \
       %{mabi=n32: /usr/local/lib32/ /lib32/ /usr/lib32/}  \
       %{mabi=64: /usr/local/lib64/ /lib64/ /usr/lib64/}"
    

    Listing 1.6-9: MIPS replacing the standard prefix chain (gcc/config/mips/mti-linux.h:37-41).

Header search gets the same treatment through SYSROOT_HEADERS_SUFFIX_SPEC, which MIPS defines as the same spec (mti-linux.h:35). The driver processes that spec at gcc.cc:8568-8577.

t-* fragments and genmultilib: declaring the variant set

A target declares its variant set in its t-* makefile fragment, through the MULTILIB_* variables, and a shell script, genmultilib, compiles that declaration into the driver. If you build a toolchain rather than use one, the fragment is where you change the variant set. The internals manual documents every variable, and the last column gives its line in fragments.texi:

VariableDeclaresfragments.texi
MULTILIB_OPTIONSthe option axes, with / between exclusive options and a space between combinable ones:64
MULTILIB_DIRNAMESthe GCC-side directory name per variant:86
MULTILIB_MATCHESoption spellings that map to the same variant:106
MULTILIB_EXCEPTIONScombinations not to build:114
MULTILIB_REQUIREDthe whitelist form of the same idea:129
MULTILIB_REUSEserve an unbuilt option set from an existing variant:152
MULTILIB_EXTRA_OPTSoptions forced into every variant build:184
MULTILIB_OSDIRNAMESthe OS-side name, optionally :multiarch after a colon:192

The x86-64 GNU/Linux fragment sets three of these variables. It computes each value instead of listing it:

comma=,
MULTILIB_OPTIONS    = $(subst $(comma),/,$(TM_MULTILIB_CONFIG))
MULTILIB_DIRNAMES   = $(patsubst m%, %, $(subst /, ,$(MULTILIB_OPTIONS)))
MULTILIB_OSDIRNAMES = m64=../lib64$(call if_multiarch,:x86_64-linux-gnu)
MULTILIB_OSDIRNAMES+= m32=$(if $(wildcard $(shell echo $(SYSTEM_HEADER_DIR))/../../usr/lib32),../lib32,../lib)$(call if_multiarch,:i386-linux-gnu)
MULTILIB_OSDIRNAMES+= mx32=../libx32$(call if_multiarch,:x86_64-linux-gnux32)

Listing 1.6-10: the multilib variables of x86-64 GNU/Linux (gcc/config/i386/t-linux64:33-38).

The six lines hold three pieces of indirection. The option list comes from TM_MULTILIB_CONFIG, which config.gcc sets from the triple, so x86_64-linux-gnu and i686-linux-gnu get different axes from the same fragment. if_multiarch emits the :name part only on a multiarch-enabled configuration, so the same line serves Debian and Fedora. The m32 line probes the filesystem at build time for usr/lib32, and falls back to ../lib when it is absent. A comment above the variables gives the reason:

On Debian, Ubuntu and other derivative distributions, the 32bit libraries are found in /lib32 and /usr/lib32, /lib64 and /usr/lib64 are symlinks to /lib and /usr/lib, while other distributions install libraries into /lib64 and /usr/lib64. The LSB does not enforce the use of /lib64 and /usr/lib64, it doesn't tell anything about the 32bit libraries on those systems.

— gcc/config/i386/t-linux64:19-24

genmultilib writes the variant set into a generated header, multilib.h (gcc/Makefile.in:2476-2483). The driver includes that header with a comment about its position:

#include "multilib.h" /* before tm.h */

Listing 1.6-11: multilib.h, included before tm.h (gcc/gcc.cc:37).

Pruning multilibs in GCC also prunes them in newlib when newlib is built in a combined tree, with its directories beside gcc/ (Chapter 3.6). In such a tree, newlib and anything else built with it take their variant set from xgcc -print-multi-lib. A --disable-multilib GCC therefore produces a single-variant newlib, whether or not you asked for one.

Three things to carry away

A variant has two directory names, not one. multilib_dir and multilib_os_dir play different roles, and a flag set when a prefix was registered decides which one that prefix gets.

Every prefix is tried up to four ways, then once more with no variant. That last pass is why a wrong-ABI link can succeed with no error.

Check that the variant exists before you debug a path. If gcc -print-multi-lib does not list it, no search order will find it.

Documentation coverage

Multilib is the best-documented mechanism in Part I. The internals manual's Target Makefile Fragments node covers the fragment variables, including the two-pass walk (gcc/doc/fragments.texi:205-210) and the ! prefix that disables it. It also gives the multiarch ordering (:218-220) and says that MULTILIB_OSDIRNAMES subsumes MULTIARCH_DIRNAME (:212-216). The GCC manual documents the -print-multi-* options under Developer Options (gcc/doc/invoke.texi:20326).

What is not documented is the consequence rather than the mechanism:

  • That the fallback pass turns a missing variant into a wrong-library link rather than an error.
  • That -print-search-dirs shows the prefix list before the multilib expansion, so its output is not the set of directories that the driver searches.

Next: Chapter 1.7, The link line: crt*.o files, -lgcc and their order, what all these paths are searched for.