1.7 The link line: crt*.o files, -lgcc and their order

GCC 15.2.0. To run the commands: an installed compiler for GNU/Linux.

You link with gcc -v and read the collect2 command at the end of the output. Five object files with crt in their names sit around your own objects, in an order that nothing on the line explains, and -lgcc appears twice.

Neither is an accident. One spec, LINK_COMMAND_SPEC, writes the whole link line, and the order of its directives is the link order. The startup files come from two unrelated providers, the C library and GCC's libgcc, so a missing one points at the sysroot or at the prefix depending on its owner. libgcc appears on both sides of the C library on purpose, because the C library can call into it.

This chapter assumes Chapter 1.1, for -### and collect2, Chapter 1.2, for the sysroot and the installation prefix, and Chapter 1.3, for the spec language, %G and Listings 1.3-5, 1.3-6 and 1.3-9. It also uses the library search list of Chapter 1.5, with %D, add_sysrooted_prefix and Listings 1.5-9 and 1.5-14, and the multilib subdirectory from Chapter 1.6.

On a glibc target, the startup objects run from crt1.o to crtn.o, with three before your own objects and two after them. Two providers supply them, the C library and GCC's libgcc, and the diagram marks which file comes from which:

crt1.o   crti.o   crtbegin.o   …your objects…   crtend.o   crtn.o
└──────  libc  ─────┘└ libgcc ┘                 └ libgcc ┘  └ libc ┘

The libraries form a second sequence, in which libgcc appears on both sides of the C library. On the link line this sequence sits between your objects and crtend.o, not after crtn.o:

-lgcc   -lc   -lgcc

To see both sequences on your own toolchain, print the link command without running it. Search for collect2 rather than ld, because on most targets the driver runs collect2, which then runs ld (Chapter 1.1):

$ gcc -### hello.c 2>&1 | grep collect2

LINK_COMMAND_SPEC is the one spec that writes the whole link command, and the position of each directive in it is the position of its output on the link line. Chapter 1.3 read it as an example of spec syntax, in Listing 1.3-6. Annotated with what each slot adds to the link line, it shows where the startup files, your objects and the libraries go:

%{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:          ← only when actually linking
    %(linker)                                       ← collect2 (or ld)
    %{flto} %{fno-lto} %{flto=*} %l                 ← target link flags
    %X %{o*} %{e*} …                                ← -Wl, options, -o, -e …
    %{!nostdlib:%{!r:%{!nostartfiles:%S}}}          ← crt1.o crti.o crtbegin.o
    %{static|no-pie|static-pie:} %@{L*} %(link_libgcc)
    %o                                              ← YOUR object files
    %{!nostdlib:%{!r:%{!nodefaultlibs:
        %(link_ssp) %(link_gcc_c_sequence)}}}       ← libgcc + libc + libgcc
    %{!nostdlib:%{!r:%{!nostartfiles:%E}}}          ← crtend.o crtn.o
    %{T*}  \n%(post_link) }}}}}}

Listing 1.7-1: LINK_COMMAND_SPEC, abridged (gcc/gcc.cc:1159-1178).

%S, %o, the libraries and %E reach the linker in that order. The startup files are split into a startfile spec and an endfile spec only because %S and %E sit on opposite sides of %o. The %{!nostdlib:…}, %{!nostartfiles:…} and %{!nodefaultlibs:…} wrappers in Listing 1.7-1 are the -no* guards that Chapter 1.3 named. Chapter 1.10 reads the full truth table off their nesting.

The %(link_libgcc) slot immediately before your objects is where the search list of Chapter 1.5 reaches the linker. Its default value is one directive, %D, which expands to one -L option per directory in the driver's prefix list. That one directive is the whole connection between the prefix list and the linker's search path:

#ifndef LINK_LIBGCC_SPEC
/* Generate -L options for startfile prefix list.  */
# define LINK_LIBGCC_SPEC "%D"
#endif

Listing 1.7-2: where the -L flags come from (gcc/gcc.cc:1180-1183).

crt1.o from libc, crtbegin.o from libgcc: one search list

crt1.o comes from the C library and crtbegin.o from libgcc, but the driver finds both through one search list. The spec text therefore does not show which provider a file has. The C library's files move with the sysroot and libgcc's with the installation prefix, and that split decides what to fix when a link cannot find a startup file:

FilesProviderInstalled underMoved by
crt1.o, Scrt1.o, gcrt1.o, crti.o, crtn.othe C librarythe sysroot's /usr/lib--with-sysroot, --sysroot
crtbegin*.o, crtend*.oGCC's libgcc$prefix/lib/gcc/<t>/<v>/--prefix, -B

Both halves are written the same way in the spec, because %s only means "look this name up in the library search list" (Listing 1.3-9). The libc half is found because /lib/ and /usr/lib/ are registered with add_sysrooted_prefix (Listing 1.5-9), and that call is where the sysroot is added to the path. The libgcc half is found through prefixes derived from the driver's own location, which are never sysrooted.

The diagnosis therefore takes one command for each half. -print-file-name walks the same search list, and when it finds no file it prints its argument back unchanged (Listing 1.5-14):

$ gcc -print-file-name=crt1.o       # the libc half
$ gcc -print-file-name=crtbegin.o   # the libgcc half
Echoed back verbatimMeans
crt1.oyour sysroot is wrong
crtbegin.oyour prefix or -B is wrong

STARTFILE_SPEC: the crt0 default and the gnu-user.h override

The default STARTFILE_SPEC in the driver is built on crt0, and the familiar crt1.o, crti.o and crtbegin.o of a glibc link come from one target family's override. To find the startup files of your own target, read its override, which for GNU user space is in gcc/config/gnu-user.h. The default in gcc.cc is one conditional:

/* config.h can define STARTFILE_SPEC to override the default crt0 files.  */
#ifndef STARTFILE_SPEC
#define STARTFILE_SPEC  \
  "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
#endif

Listing 1.7-3: the default STARTFILE_SPEC (gcc/gcc.cc:891-895). The default ENDFILE_SPEC, at :897-900, is the empty string.

That default is a historical fallback that almost no target uses. GNU user space installs its own startfile spec over it:

#define GNU_USER_TARGET_STARTFILE_SPEC \
  "%{shared:; \
     pg|p|profile:%{static-pie:grcrt1.o%s;:gcrt1.o%s}; \
     static:crt1.o%s; \
     static-pie:rcrt1.o%s; \
     " PIE_SPEC ":Scrt1.o%s; \
     :crt1.o%s} " \
   GNU_USER_TARGET_CRTI " \
   %{static:crtbeginT.o%s; \
     shared|static-pie|" PIE_SPEC ":crtbeginS.o%s; \
     :crtbegin.o%s} \
   ...

Listing 1.7-4: the glibc startfile spec (gcc/config/gnu-user.h:51-65, installed over the default at :66-67).

This spec is the best example in the tree of the ;-separated if/else-if/else form from Chapter 1.3. Its first selection has six arms, and each one picks a single crt1 variant or none:

You passedYou get
-sharednothing (the empty first arm)
-pg, -p or -profilegcrt1.o, or grcrt1.o with -static-pie
-staticcrt1.o
-static-piercrt1.o
whatever PIE_SPEC matchesScrt1.o
otherwisecrt1.o

A second, independent selection picks crtbeginT.o, crtbeginS.o or crtbegin.o. Because both selections depend on the flags, gcc -static -### hello.c and gcc -shared -### hello.c produce link lines that share almost no startup objects, and "the crt1 file" is not a well-defined phrase.

The matching ENDFILE_SPEC mirrors the whole structure (gcc/config/gnu-user.h:75-85). The crti.o in the startfile spec and the crtn.o in the endfile spec come from two one-line macros:

#define GNU_USER_TARGET_CRTI "crti.o%s"
#define GNU_USER_TARGET_CRTN "crtn.o%s"

Listing 1.7-5: GNU_USER_TARGET_CRTI and GNU_USER_TARGET_CRTN (gcc/config/gnu-user.h:43-44).

extra_parts: when libgcc supplies crti.o

extra_parts declares which crt* files a target's libgcc provides, and on many bare-metal targets the list includes crti.o. On such a target a missing crti.o means your prefix is wrong, not your sysroot, so the -print-file-name diagnosis for a glibc link does not apply. Check what your libgcc installed before you blame either setting.

Each target's list is in libgcc/config.host. For example, arm*-*-eabi* gets extra_parts="crtbegin.o crtend.o crti.o crtn.o" (libgcc/config.host:584). libgcc's makefile turns extra_parts into EXTRA_PARTS (libgcc/Makefile.in:59-61) and installs them into inst_libdir, which is libsubdir plus the multilib subdirectory from Chapter 1.6:

inst_libdir = $(libsubdir)$(MULTISUBDIR)

Listing 1.7-6: where libgcc's objects land (libgcc/Makefile.in:315; the install rule is install-leaf at :1188).

libgcc computes libsubdir from real_host_noncanonical, not from a target variable (libgcc/Makefile.in:204), because libgcc is configured with --host=<GCC's target>. Whenever a path formula in a target library says "host", read "GCC's target". The same convention returns in Chapter 1.12, in the install paths of libstdc++.

What libgcc is: the library the compiler emits calls into

libgcc is GCC's own runtime support library, and the compiler emits calls into it whether or not you asked for it. Those calls explain both of its surprises on the link line: it appears twice, and a -nostdlib link still needs it. The calls go to four kinds of helper:

  • integer division and modulo helpers on targets without the instruction, such as __divdi3 and __udivsi3
  • the __aeabi_* helpers on Arm EABI targets such as arm-none-eabi, whose names come from Arm's run-time ABI document rather than from GCC (gcc/config/arm/arm.cc:2573-2666, explained in Chapter 4.1)
  • soft-float emulation
  • the stack unwinder used by C++ exceptions and by __attribute__((cleanup))

Dropping the standard libraries does not stop the compiler from emitting a call to __aeabi_idiv, so you still need -lgcc under -nostdlib. The GCC manual's -nostdlib entry under Link Options gives the same advice. The most common result of leaving it out is a bare-metal link that fails on an undefined __aeabi_* or __udivsi3. Chapter 1.10 covers what a link still needs once you have taken the runtime away.

The default library sequence is -lgcc -lc -lgcc because the C library can call into libgcc, for __divdi3 on a target without a division instruction, for the unwinder or for soft-float helpers. With static archives the linker resolves left to right, and it takes from an archive only the members it needs at the moment it reads that archive. A reference that libc.a creates after libgcc.a has been scanned would go unresolved, so libgcc is repeated after libc:

-lgcc   -lc   -lgcc
 │       │     └── libgcc AGAIN, after libc
 │       └──────── libc
 └──────────────── libgcc

One spec writes that sequence, and its comment says why it is a spec of its own rather than a part of LINK_COMMAND_SPEC:

/* This is overridable by the target in case they need to specify the
   -lgcc and -lc order specially, yet not require them to override all
   of LINK_COMMAND_SPEC.  */
#ifndef LINK_GCC_C_SEQUENCE_SPEC
#define LINK_GCC_C_SEQUENCE_SPEC "%G %{!nolibc:%L %G}"
#endif

Listing 1.7-7: the double libgcc (gcc/gcc.cc:987-992). %G is the libgcc spec, %L the lib spec.

Two families of targets replace the default. GNU/Linux keeps -lgcc -lc -lgcc for a dynamic link. With -static or -static-pie it uses --start-group %G %L --end-group instead (gcc/config/gnu-user.h:112-117), so libgcc appears once, and the group makes the linker rescan both archives until no new reference is left. Bare-metal Arm always uses the group, because newlib's printf can reach the unwinder through libgcc's division helpers, and the unwinder calls abort in libc (gcc/config/arm/unknown-elf.h:91-96).

-nolibc drops %L %G, the -lc and the second -lgcc, and keeps the leading -lgcc, because in Listing 1.7-7 the %{!nolibc:…} wraps %L %G and not the first %G. The GCC manual documents -nolibc and the rest of the -no* family under Link Options.

%G and %L: what the libgcc and lib specs expand to

%G and %L name the libgcc and lib specs, and neither always expands to the single option its name suggests. On a shared-libgcc target %G depends on the static and shared options of the link, and %L has a default that most targets override. Two links from the same toolchain can therefore name different libraries.

The driver rewrites the libgcc slot at startup (Listing 1.3-5), into a nested conditional that chooses between -lgcc -lgcc_eh, -lgcc --as-needed -lgcc_s --no-as-needed and -lgcc_s -lgcc, depending on -static, -static-libgcc and -shared-libgcc. With a recent GNU ld, --push-state --as-needed … --pop-state takes the place of --as-needed … --no-as-needed. These two commands therefore give different answers on the same toolchain:

$ gcc -### foo.o 2>&1 | tr ' ' '\n' | grep lgcc
$ gcc -### -static foo.o 2>&1 | tr ' ' '\n' | grep lgcc

Without -static the output names -lgcc_s, and with -static it names -lgcc_eh in its place, as the table of cases in Chapter 1.3 shows.

The lib spec has a default too: -lc, -lc_p under profiling, and nothing when building a shared object. Most targets override it in their config/*.h:

/* config.h can define LIB_SPEC to override the default libraries.  */
#ifndef LIB_SPEC
#define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
#endif

Listing 1.7-8: the default LIB_SPEC (gcc/gcc.cc:754-757).

-nostdlib, -nostartfiles and -nodefaultlibs each fail one or more guards in LINK_COMMAND_SPEC, and the text inside a failed guard leaves the link line. Comparing the -### output with and without each flag shows which pieces go, and it is the quickest way to learn the template. The last command prints the template as your driver holds it:

$ gcc -### hello.c                    # baseline
$ gcc -### -nostdlib hello.c          # crt*.o and -lc/-lgcc gone
$ gcc -### -nostartfiles hello.c      # crt*.o gone, -lc/-lgcc kept
$ gcc -### -nodefaultlibs hello.c     # crt*.o kept, -lc/-lgcc gone
$ gcc -dumpspecs | grep -A2 '^\*link_command'

Each piece that disappears sat inside a %{!…:} guard that the flag fails.

Three things to carry away

The startup files come from two providers. crt1.o, crti.o and crtn.o are the C library's, crtbegin.o and crtend.o are libgcc's, and on some bare-metal targets crti.o is libgcc's too.

-lgcc appears twice on purpose. libc can call into libgcc, and the linker takes from a static archive only what is undefined when it reads that archive.

The compiler emits calls into libgcc whatever you link. That is why a -nostdlib link still needs -lgcc.

Things that surprise people

g++ moves your -lm and -lc. It takes them out of wherever you put them and emits them again after -lstdc++, with no diagnostic. On a target where every library is a static archive, that move changes symbol resolution (Chapter 1.11).

-r fails the same guards as -nostdlib. A relocatable link never gets the runtime, because %{!r: appears in each of the three guards in Listing 1.7-1.

-static-libstdc++ is not on the link line on most targets. The C++ driver consumes it and puts -Wl,-Bstatic … -Wl,-Bdynamic around one -l instead, so search the link line for Bstatic, not for the option (Chapter 1.11).

ENDFILE_SPEC is empty by default. A link line with no crtend.o may be correct for your target, if the target keeps that default.

A successful link says nothing about run time. Finding libstdc++.so.6 or libc.so.6 when the program starts is the job of the target's dynamic loader, through DT_RUNPATH, ld.so.conf and LD_LIBRARY_PATH. Link-time search and run-time search are unrelated systems that happen to involve some of the same file names.

Documentation coverage

The GCC manual documents -nostdlib and the other -no* options under Link Options (gcc/doc/invoke.texi:19067). The internals manual has a chapter on libgcc, The GCC low-level runtime library (gcc/doc/libgcc.texi:6).

What is not documented:

  • Why -lgcc appears twice. The spec is in the source, but the rationale is not, and you have to reconstruct it. The nearest thing is the comment in Listing 1.7-7, which explains why the ordering is overridable rather than why it is what it is.
  • That the default STARTFILE_SPEC is built on crt0, and that the familiar crt1/crti/crtbegin shape is a per-target-family override. Every secondhand account of GCC's link order presents one target's spec as universal.
  • That crti.o may come from libgcc rather than libc, which inverts the -print-file-name diagnosis on bare-metal targets.

Next: Chapter 1.8, Where <stdint.h> comes from: the headers GCC ships, the same question for headers.