1.10 -nostdlib and -ffreestanding: turning the runtime off
GCC 15.2.0. To run the commands: an installed compiler, and arm-none-eabi-gcc for the bare-metal examples.
You are bringing up firmware on a Cortex-M part. There is no operating system,
no glibc and no crt1.o that knows how to call main, so you reach for
-nostdlib. The link then fails on an undefined reference to __aeabi_idiv,
a symbol you have never typed, from a library you thought you had switched off.
-nostdlib is not one mechanism. In the link spec it is three %{!…:} guards,
and in the g++ driver it is one case label. Where those guards sit decides
what each option of the family removes, so the truth table can be read from the
source instead of memorised from the manual. -nostdlib also does not stop the
compiler from emitting calls into libgcc, and whatever it removes, your startup
code and link line must now supply. Three options with similar names,
-ffreestanding, -nostdinc and -nostdinc++, act before the link and leave
it alone.
This chapter assumes Chapter 1.1 for -###, and
Chapter 1.3 for the spec language and its %{…}
conditionals. It takes apart the link line that
Chapter 1.7 built, and uses its Listing 1.7-1 of
LINK_COMMAND_SPEC, its startfile and endfile specs and its double -lgcc. It
also uses the search lists of Chapter 1.5, the
multilib selection of Chapter 1.6 and the include table
cpp_include_defaults of Chapter 1.8.
The -nostdlib family in common.opt: Driver and no variable
-nostdlib and the four other options of its family have no C variable
anywhere in the compiler. They exist as strings that a spec conditional such as
%{!nostdlib:…} can match, which is why they compose cleanly and why a search
of the source for flag_nostdlib finds nothing. Each is declared with the
single flag Driver and nothing else:
nodefaultlibs
Driver
nostartfiles
Driver
nolibc
Driver
nostdlib
Driver
nostdlib++
Driver
Listing 1.10-1: the whole declaration of every option in the -nostdlib family
(gcc/common.opt:3782-3795).
No declaration has a Var(...), an Init(...) or help text. An option with
Driver and no Var therefore cannot be tested with an if anywhere in the
compiler.
-nostdlib++ was added in GCC 13, so it does not exist if you are on GCC 12 or
earlier. The option is absent from gcc/common.opt at releases/gcc-11.4.0
and releases/gcc-12.3.0, and present from releases/gcc-13.3.0 onward.
-nolibc and -nostdlib go back much further.
The guards in LINK_COMMAND_SPEC: the truth table is their nesting
The truth table of the -nostdlib family follows from three lines of
LINK_COMMAND_SPEC, each holding one slot guarded three deep. The outer two
guards are the same on all three lines, and only the inner one differs.
Chapter 1.7 showed the whole template as Listing
1.7-1, and these are its guarded slots:
%{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!r:%{!nostartfiles:%S}}} \
...
%{!nostdlib:%{!r:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}}\
%{!nostdlib:%{!r:%{!nostartfiles:%E}}} %{T*} \n%(post_link) }}}}}}"
Listing 1.10-2: the three guarded slots, at gcc/gcc.cc:1168,
:1176 and :1177.
Reading the guards from the outside in gives the slots that each option suppresses. An option suppresses a slot when its name sits in one of that line's guards:
| Option | Suppresses %S (startfiles) | Suppresses %(link_gcc_c_sequence) | Suppresses %E (endfiles) |
|---|---|---|---|
-nostartfiles | yes | no | yes |
-nodefaultlibs | no | yes | no |
-nostdlib | yes | yes | yes |
-r | yes | yes | yes |
The GCC manual documents the first three rows, with -nolibc and
-nostdlib++, under Link Options. The -r row follows from
the outer guards, which are %{!nostdlib:%{!r: on every line, so -r and
-nostdlib are indistinguishable in these slots. A relocatable link therefore
never gets the runtime. If you pass -r and find crtbegin.o missing, this
guard is the cause. The behaviour is correct, because a partial link must not
drag in startup code that will be linked again later.
-nostartfiles and -nodefaultlibs differ only in which lines carry their
inner guard. -nostartfiles sits in the guards of the %S and %E lines, and
-nodefaultlibs in the guard of the library line. Nothing enforces this
symmetry, which comes only from the option name written inside each %{!…:}.
Checking -nostdlib, -nostartfiles and -nodefaultlibs with -###
Each row of the truth table can be checked with -###, which prints the
command lines the driver would run and then stops. Diffing that output with and
without each option shows which crt* files and -l options leave the link
line. The GCC manual documents -### under Overall Options,
and these commands filter its output down to the crt files and -l options:
$ gcc -### hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > full
$ gcc -### -nostdlib hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > nostdlib
$ gcc -### -nostartfiles hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > nostart
$ gcc -### -nodefaultlibs hello.c 2>&1 | tr ' ' '\n' | grep -E 'crt|^-l' | sort > nodeflibs
$ diff full nostart # only crt* lines disappear
$ diff full nodeflibs # only -l* lines disappear
$ diff full nostdlib # both
$ gcc -### -r hello.c 2>&1 | tr ' ' '\n' | grep -cE 'crt|^-l' # 0, same as -nostdlib
Listing 1.10-3: deriving the truth table experimentally.
The first diff shows only crt* lines leaving, the second only -l lines,
and the third both. Under -r the last command counts no crt file and no
-l option, the same result as -nostdlib. The sort matters, because
-nodefaultlibs also changes the order of what is left.
The -no* link options change no search path, because they remove text from a
command line and never touch where the driver looks. -print-search-dirs and
-print-file-name=crt1.o give the same answers with and without each of them.
%S, %E and %G %L %G: what each guard removes
The three guards remove the directives %S, %E and %(link_gcc_c_sequence),
not named files, so what an option takes off the link line depends on what the
target's specs expand to. %S and %E are the startfile and endfile specs from
Chapter 1.7, and the library slot is a sequence that
holds more than -lc. Knowing each expansion tells you what a -nostdlib link
has to put back.
The default startfile spec is built on crt0, and the default endfile spec is
empty (gcc/gcc.cc:891-895, :897-900). The
familiar crt1.o crti.o crtbegin.o shape is the GNU userspace override. What
-nostartfiles removes is therefore target-specific: on glibc it is five
objects, and on a target that never defined STARTFILE_SPEC it may be one.
The library slot holds %(link_gcc_c_sequence), which is not -lc. Its
default is a macro that a target can override:
#ifndef LINK_GCC_C_SEQUENCE_SPEC
#define LINK_GCC_C_SEQUENCE_SPEC "%G %{!nolibc:%L %G}"
#endif
Listing 1.10-4: LINK_GCC_C_SEQUENCE_SPEC (gcc/gcc.cc:987-992).
%G is libgcc and %L is libc, so the sequence is -lgcc -lc -lgcc, the
double libgcc that Chapter 1.7 explains.
-nodefaultlibs removes the whole expression, while -nolibc removes only
%L %G, the -lc and the second -lgcc, and keeps the leading -lgcc. That
makes -nolibc the option for a link that has its own libc but still wants the
compiler's helper routines. The definition is byte-identical in every release
from GCC 11 to 15.2.0.
-nostdlib removes -lgcc, not the calls into libgcc
-nostdlib removes -lgcc from the link line, but not the calls to libgcc
that the compiler has already emitted into your object files. Those calls are
why the firmware link fails on __aeabi_idiv. An undefined __aeabi_idiv or
__udivsi3 after a -nostdlib link is the most common consequence of the
option, and it always has the same fix: put -lgcc back by hand.
The compiler emits a libgcc call when the target has no instruction for what
you wrote: a 64-bit divide on a 32-bit machine, a soft-float multiply, an
unaligned wide load or a switch lowered to a table helper. On Arm the helpers
are the __aeabi_* family, and elsewhere they have names such as __divdi3,
__udivsi3 and __muldf3. The GCC manual's -nostdlib entry under
Link Options gives the same warning and tells you to add
-lgcc back. nm -u shows the calls in an object file before any link runs:
$ arm-none-eabi-gcc -c -O2 -mcpu=cortex-m0 div.c
$ arm-none-eabi-nm -u div.o | grep aeabi
Listing 1.10-5: the calls survive -nostdlib because they were emitted at compile
time, long before the link line existed.
If div.c contains a division, nm -u lists the __aeabi_* helpers that
div.o calls among its undefined symbols, although no link has run yet. A
working bare-metal link is therefore almost never bare -nostdlib. It puts
libgcc back by hand, next to its own linker script and startup object:
$ arm-none-eabi-gcc -nostdlib -T link.ld start.o main.o -lgcc
-print-libgcc-file-name prints the full path of the libgcc.a that -lgcc
finds with the options you give it. The GCC manual documents it for this case
under Developer Options:
$ arm-none-eabi-gcc -mcpu=cortex-m4 -mfloat-abi=hard -print-libgcc-file-name
The path goes through the multilib selection of
Chapter 1.6, so the answer changes with -mcpu and
-mfloat-abi. A libgcc.a from the wrong variant links and then misbehaves.
-lstdc++ comes from the g++ driver, not from a spec
-lstdc++ is not in any spec, so no %{!…:} guard can remove it. The g++
driver adds it before the specs run, and checks the -no* options itself to
decide whether to add it. It checks a different set of options from the spec
guards, so a g++ link has a fourth column that the truth table does not
predict:
case OPT_nostdlib__:
args[i] |= SKIPOPT;
/* FALLTHRU */
case OPT_nostdlib:
case OPT_nodefaultlibs:
library = -1;
break;
Listing 1.10-6: the C++ side of the family (gcc/cp/g++spec.cc:170-176).
Setting library to -1 means "never link the C++ runtime", according to the
comment on its values (gcc/cp/g++spec.cc:92-97). Three
consequences follow that the spec guards do not predict.
-nostartfiles does not suppress -lstdc++, because it is not in that case
list. The startfiles and the C++ runtime are decided by two unrelated pieces of
code, and this is where the symmetry of the truth table breaks.
-r still sets library to -1, by a different route. It is absent from
Listing 1.10-6 but present a few lines further down, in the list with -c,
-S and -E (g++spec.cc:215-225). The comment there gives the
reason: "Don't specify libraries if we won't link, since that would cause a
warning."
-nostdlib++ disappears from the command line. The SKIPOPT on the first line
of Listing 1.10-6 deletes it from the option array, and the /* FALLTHRU */
gives it the same library = -1 as -nostdlib. Unlike -nostdlib, it never
reaches the specs, so it drops the C++ runtime and leaves -lc and -lgcc in
place. Chapter 1.11 reads that state machine in
full.
-nostdlib, -ffreestanding, -nostdinc: related names, unrelated stages
-nostdlib, -ffreestanding and -nostdinc have related names but act at
three different stages, and none of them implies another. The names invite
confusion, but each option is implemented in a different part of the compiler
and changes something different:
| Option | Stage | What it changes |
|---|---|---|
-nostdlib | link | text on the linker command line |
-ffreestanding | compile | what the compiler may assume about libc and main |
-nostdinc / -nostdinc++ | preprocess | the header search list |
You can #include <stdio.h> under -nostdlib and fail only at link, and you
can pass -ffreestanding and see no change in the link line. The GCC manual
keeps them apart too: -ffreestanding is under
C Dialect Options, and -nostdinc and -nostdinc++ are
under Directory Options. -ffreestanding and -nostdinc are
both handled in gcc/c-family/c-opts.cc, and each does more than its name
suggests.
-ffreestanding sets flag_hosted and flag_no_builtin
-ffreestanding sets two flags, flag_hosted and flag_no_builtin, and the
second has the more visible effects. The common account says only that it sets
flag_hosted to 0, but the manual's entry under
C Dialect Options says that the option "implies
-fno-builtin". The source sets the two flags together:
case OPT_ffreestanding:
value = !value;
/* Fall through. */
case OPT_fhosted:
flag_hosted = value;
flag_no_builtin = !value;
break;
Listing 1.10-7: gcc/c-family/c-opts.cc:498-504.
__STDC_HOSTED__ is defined from flag_hosted, which also relaxes the
requirements on main. flag_no_builtin stops the compiler from turning
printf("x\n") into puts("x"), or memcpy into inline moves. Two further
effects of -ffreestanding sit in the same file: loop pattern recognition is
disabled (c-opts.cc:935-939), and the -Wmain default
flips (:947-954). -ffreestanding is therefore closer to
-fno-builtin than to -nostdlib.
-nostdinc removes GCC's own headers too
-nostdinc removes every standard include directory, GCC's own include
directory among them, so <stdint.h> goes along with <stdio.h>. The whole
implementation is one file-static bool and the if that tests it. The option
sets the bool:
case OPT_nostdinc:
std_inc = false;
break;
Listing 1.10-8: gcc/c-family/c-opts.cc:639-641.
The bool is passed as the stdinc parameter of register_include_chains
(gcc/c-family/c-opts.cc:867-868). There it gates one call:
/* Finally chain on the standard directories. */
if (stdinc)
add_standard_paths (sysroot, iprefix, imultilib, cxx_stdinc);
Listing 1.10-9: the entire implementation of -nostdinc
(gcc/incpath.cc:512-514).
add_standard_paths walks cpp_include_defaults, the table from
Chapter 1.8 that holds both /usr/include and
GCC's own lib/gcc/<target>/<version>/include. One if skips the whole table,
and with it the directory holding <stddef.h>, <stdint.h> and <stdarg.h>,
which Chapter 1.8 showed the compiler is required to provide. The useful form
is therefore almost always a pair, which drops the system headers and keeps the
compiler's own:
$ gcc -nostdinc -isystem "$(gcc -print-file-name=include)" -c foo.c
Listing 1.10-10: drop the system headers, keep the compiler's own.
The -isystem directory survives because it goes on a chain that is merged
after add_standard_paths would have run. -v prints the search list that
results, so you can confirm what -nostdinc leaves:
$ echo 'int main(void){return 0;}' | gcc -nostdinc -E -v -x c - 2>&1 | sed -n '/search starts here/,/End of search/p'
The list that sed prints holds neither GCC's own include directory nor
/usr/include, because the if in Listing 1.10-9 skipped the table that names
them. Adding the -isystem of Listing 1.10-10 puts GCC's own directory back.
-nostdinc++ is narrower. It sets std_cxx_inc to false, which arrives as
cxx_stdinc and suppresses only the entries whose cplusplus field is
non-zero (gcc/incpath.cc:176-177). Those are the C++
directories in Chapter 1.8's table, so the C headers stay.
After -nostdlib: _start, constructors, -lgcc and a libc
A -nostdlib link leaves four jobs to you that the startfiles and the default
libraries used to do. The first two produce a program that links, runs and
does the wrong thing, rather than one that fails to build:
-
An entry point. The linker's default is
_start, notmain. Nothing now callsmain, sets up the stack or zeroes.bss. -
Static initialisation. The compiler puts constructors in
.init_array, but something must run them at startup. Where a target uses.init_array,crtstuff.cleaves that to the C library: "If we are using .init_array, there is nothing to do" (libgcc/crtstuff.c:687). The C library's startup code begins in thecrt1.othat-nostartfilesremoves. Without it, C++ constructors for file-scope objects and C__attribute__((constructor))functions never run, with no diagnostic. -
libgcc. Add
-lgccby hand, because the calls that the compiler emitted into libgcc survive-nostdlib. -
A C library. Supply one, or write code that needs none.
-nolibcis the middle ground, which keeps-lgccand drops-lc.
Three things to carry away
-nostdlib is three spec guards and one case label. -nostartfiles and
-nodefaultlibs fail some of the same guards, and -r fails all three.
Removing -lgcc does not remove the calls to it. The compiler emitted them
when it compiled your code, so a bare-metal link still needs libgcc.
-nostdlib, -ffreestanding and -nostdinc act at three different stages.
The stages are link, compile and preprocess, and none of the three options
implies another.
Things that surprise people
The -no* link options change no search path. Removing -lc does not
remove <sysroot>/usr/lib from the search list. Chapter 1.7's rule holds: the
driver emits text, and ld resolves it.
-nostdlib and -ffreestanding are often used together and do not
overlap. A hermetic build needs all three,
-nostdlib -ffreestanding -nostdinc, plus explicit -I, -L and --sysroot.
A missing constructor is a -nostartfiles bug. If your C++ globals are
uninitialised and nothing crashed, look for the startup objects on the link
line, crt1.o among them on glibc, before looking anywhere else.
-nolibc exists. A link with -nodefaultlibs and -lgcc added back by
hand gets what -nolibc gives in one option, except that -nodefaultlibs also
drops %(link_ssp), which -nolibc keeps.
Documentation coverage
The GCC manual documents the link options in the Link Options
node (gcc/doc/invoke.texi:19067), and it documents what each one
suppresses. -ffreestanding is under C Dialect Options,
and -nostdinc under Directory Options.
What is not documented:
- That the link options are pure spec conditionals with no C variable. The manual
describes the effect, but nothing says that the implementation is three
%{!…:}guards. That fact is what lets you predict the interactions instead of memorising them. - That
-ris equivalent to-nostdlibfor all three slots. You can only get this by reading the%{!r:in Listing 1.10-2. - That
-nostdincremoves GCC's own headers as well as the system's. The manual implies it: only the-I,-iquote,-isystemand-idirafterdirectories are searched (gcc/doc/cppdiropts.texi:142-147). But neither the manual nor the help text, "standard system include directories", names GCC's ownincludedirectory. Listing 1.10-9 states it. - That
-lstdc++is removed by a different mechanism, and therefore that the truth table has an asymmetric fourth column. Nothing in the manual connects the two families.
Next: Chapter 1.11, How g++ injects -lstdc++,
the function that puts -lstdc++ on a g++ link and moves your -lm.