1.11 How g++ injects -lstdc++

GCC 15.2.0. To run the commands: an installed compiler with g++.

You have a project of C object files, and nothing in it is C++. You link it with g++, because that is what the build system uses, and you pass -lm -lz because you need the maths library and zlib. The link line that comes out has -lstdc++ on it, and your -lm has moved: you typed it before -lz, and it comes out after -lstdc++.

g++ runs the same driver code as gcc, with one extra function called before any option is acted on. That function may rewrite the option array: insert options, delete them and reorder them. Everything surprising about C++ linking happens in those few hundred lines of gcc/cp/g++spec.cc, and the manual documents only their outcome.

This chapter assumes Chapter 1.1, for -### and the call to lang_specific_driver in Listing 1.1-8, and Chapter 1.3, for specs and -dumpspecs. It also assumes Chapter 1.7, for the link line that the generic driver builds from LINK_COMMAND_SPEC, and Chapter 1.10, for -nostdlib, -nostartfiles and the truth table of their spec guards.

lang_specific_driver: the g++ hook called before any option acts

lang_specific_driver is the hook that makes g++ differ from gcc. It runs before the driver acts on any option, so it can rewrite your command line before anything reads it. The generic driver first decodes argv into an array of struct cl_decoded_option, then makes the call that Chapter 1.1 showed as Listing 1.1-8:

  /* Do language-specific adjustment/addition of flags.  */
  lang_specific_driver (&decoded_options, &decoded_options_count,
			&added_libraries);

Listing 1.11-1: the call to the language hook (gcc/gcc.cc:4860-4862).

All three arguments are passed by address because they are out-parameters. The hook may replace the array, change its length, and report how many libraries it added. Every front end links its own lang_specific_driver: the C one does nothing, and the C++ one is in gcc/cp/g++spec.cc.

The GCC manual documents the outcome under Invoking G++: g++ "automatically specifies linking against the C++ library", and gcc does not. The manual gives no conditions, so the sections that follow read them from g++spec.cc.

Because the hook runs first, -lstdc++ is an ordinary -l by the time the specs run, no different from one you typed. No spec mentions it, so searching -dumpspecs output for stdc++ finds nothing.

library and the per-argument bits: what the hook records

The hook keeps its decision about the C++ runtime in one int, library, and what it saw in each option in an array of bits. The options that turn injection on and off move library, and the reordering of -lm and -lc reads the bits. The comment above library is the only place its four values are documented:

  /* What action to take for the c++ runtime library:
    -1  means we should not link it in.
     0  means we should link it if it is needed.
     1  means it is needed and should be linked in.
     2  means it is needed but should be linked statically.  */
  int library = 0;

Listing 1.11-2: gcc/cp/g++spec.cc:92-97.

The default is 0, "link it if it is needed", and the first pass over the options exists to move it off zero. Because the start value is the "maybe" state and not "no", most transitions go from 0 to 1. They are guarded by if (library == 0), so that an earlier -1 is never overwritten.

The bits live in a parallel array, args, with one int per option. Each #define names one bit, and its comment says what the bit records:

/* This bit is set if we saw a `-xfoo' language specification.  */
#define LANGSPEC	(1<<1)
/* This bit is set if they did `-lm' or `-lmath'.  */
#define MATHLIB		(1<<2)
/* This bit is set if they did `-lc'.  */
#define WITHLIBC	(1<<3)
/* Skip this option.  */
#define SKIPOPT		(1<<4)
/* Add -lstdc++exp for experimental features that need library support.  */
#define EXPERIMENTAL	(1<<5)

Listing 1.11-3: the per-argument bits (gcc/cp/g++spec.cc:26-35).

The hook sets and tests four of those five bits. EXPERIMENTAL is never used: the #define is its only occurrence in the file, at every release from 13.3.0 to 15.2.0. The hook tracks -fcontracts with a separate bool need_experimental instead. EXPERIMENTAL is one of two pieces of unused state in the file, and the other is saw_time in the reordering of -lm and -lc. Both matter only so that you stop looking for the code that sets them.

What turns -lstdc++ injection on

Two paths move library from 0 to 1: an -l option that the hook does not recognise, and an input file that is not a header. Both are broader than "link the C++ runtime when a C++ source is on the command line", and they explain the -lstdc++ on the all-C link of the opening example.

Any -l other than -lm and -lc

The hook recognises two libraries by name, MATH_LIBRARY and c, and treats every other -l as one that might need the C++ runtime. MATH_LIBRARY is "m" by default:

	case OPT_l:
	  if (strcmp (arg, MATH_LIBRARY) == 0)
	    {
	      args[i] |= MATHLIB;
	      need_math = 0;
	    }
	  else if (strcmp (arg, "c") == 0)
	    args[i] |= WITHLIBC;
	  else
	    /* Unrecognized libraries (e.g. -lfoo) may require libstdc++.  */
	    library = (library == 0) ? 1 : library;
	  break;

Listing 1.11-4: gcc/cp/g++spec.cc:178-189.

Every library other than those two is unknown, and an unknown library might need the C++ runtime, so g++ -lz foo.o links libstdc++ because of -lz. The comment in Listing 1.11-4 is the hook's only justification. -Xlinker and -Wl, do the same (gcc/cp/g++spec.cc:207-213), with a comment that spells out the reasoning: "Arguments that go directly to the linker might be .o files, or something, and so might cause libstdc++ to be needed."

Any input other than .h, .hpp and other headers

An input file sets library to 1 unless its name ends in a header suffix. The test is negative, so the rule is not "a C++ source file on the command line": the hook never looks for a C++ extension. Listing 1.11-5 shows four of the nine suffixes it compares:

	    /* If we don't know that this is a header file, we might
	       need to be linking in the libraries.  */
	    if (library == 0)
	      {
		if ((len <= 2 || strcmp (arg + (len - 2), ".H") != 0)
		    && (len <= 2 || strcmp (arg + (len - 2), ".h") != 0)
		    && (len <= 4 || strcmp (arg + (len - 4), ".hpp") != 0)
		    ...
		    && (len <= 3 || strcmp (arg + (len - 3), ".hh") != 0))
		  library = 1;
	      }

Listing 1.11-5: abridged from gcc/cp/g++spec.cc:277-291.

The nine suffixes are .H, .h, .hpp, .hp, .hxx, .h++, .HPP, .tcc and .hh. g++ foo.o, g++ foo.a and g++ foo.s therefore all link the C++ runtime, because none of those names ends in one of them.

The two paths together give the rule: g++ links libstdc++ unless you gave it nothing but headers or an option turns the runtime off. The driver errs towards linking on purpose, because a missing -lstdc++ gives a confusing undefined-symbol error, while a spurious one costs a DT_NEEDED entry.

Three -### commands check the input-file rule and its limits. Each splits the printed commands into words and counts the words that contain stdc:

$ g++ -### foo.o        2>&1 | tr ' ' '\n' | grep -c stdc      # 1: input file rule
$ g++ -### foo.hh       2>&1 | tr ' ' '\n' | grep -c stdc      # 0: header, no link anyway
$ gcc -### foo.o -lz    2>&1 | tr ' ' '\n' | grep -c stdc      # 0: gcc injects nothing

Listing 1.11-6: the injection rules, one command each.

The object file gets its -lstdc++ from the input-file rule. The header gets none, and would not be linked in any case. gcc adds nothing even with -lz on the line, because only the g++ hook injects the C++ runtime.

What turns -lstdc++ injection off: -nostdlib and -c

Two lists of options set library to -1, which turns injection off: the -nostdlib family, and the options under which no link happens. Chapter 1.10 read the spec guards that -nostdlib trips on the link line. Listing 1.11-7 is its C++ half, which Chapter 1.10 also showed as Listing 1.10-6:

	case OPT_nostdlib__:
	  args[i] |= SKIPOPT;
	  /* FALLTHRU */
	case OPT_nostdlib:
	case OPT_nodefaultlibs:
	  library = -1;
	  break;

Listing 1.11-7: gcc/cp/g++spec.cc:170-176.

A separate case list holds the options under which no link happens at all, and its comment gives the reason:

	case OPT_c:
	case OPT_r:
	case OPT_S:
	case OPT_E:
	case OPT_M:
	case OPT_MM:
	case OPT_fsyntax_only:
	  /* Don't specify libraries if we won't link, since that would
	     cause a warning.  */
	  library = -1;
	  break;

Listing 1.11-8: gcc/cp/g++spec.cc:215-225.

Listing 1.11-8 is why g++ -c foo.cc produces no unused-argument warning, and why -r lands at -1 even though it is absent from Listing 1.11-7.

-nostartfiles is in neither list, so it does not suppress -lstdc++. A g++ link has a -lstdc++ column that the truth table of Chapter 1.10 does not predict, because these two case lists decide it, not the %{!…:} guards in LINK_COMMAND_SPEC.

-nostdlib++ is the one option in Listing 1.11-7 that disappears from the command line. It takes SKIPOPT before it falls through, so the hook deletes it from the array (gcc/cp/g++spec.cc:368-369) and it never reaches the specs. It removes the C++ runtime and leaves -lc and -lgcc in place, which is what its name promises and what -nostdlib cannot do. The GCC manual documents the option under Link Options in one line: "Do not implicitly link with standard C++ libraries."

-nostdlib++ does not exist in GCC 12 and earlier. It arrived in GCC 13, along with -lstdc++exp, and the same commit took g++spec.cc from 436 to 460 lines, so every line number in this chapter differs before GCC 13. Before GCC 12 the file is g++spec.c, not .cc.

g++ moves -lm and -lc after -lstdc++

g++ takes -lm and -lc out of their place on the command line and re-emits them after -lstdc++, which is the move in the opening example. The hook copies the options into a new array one at a time. While library is above 0, two checks in that loop pull out the first -lm and the first -lc as they pass. The comment above the checks gives the reason:

      /* Make sure -lstdc++ is before the math library, since libstdc++
	 itself uses those math routines.  */
      if (!saw_math && (args[i] & MATHLIB) && library > 0)
	{
	  --j;
	  saw_math = &decoded_options[i];
	}

      if (!saw_libc && (args[i] & WITHLIBC) && library > 0)
	{
	  --j;
	  saw_libc = &decoded_options[i];
	}

Listing 1.11-9: gcc/cp/g++spec.cc:326-338.

The --j is the removal. The loop has already written the option to new_decoded_options[j], so decrementing j lets the next iteration overwrite it. A pointer keeps the option, and the end of the hook re-emits it after the runtime:

  if (saw_math)
    new_decoded_options[j++] = *saw_math;
  else if (library > 0 && need_math)
    { ... generate_option (OPT_l, MATH_LIBRARY, ...) ... }
  if (saw_time)
    new_decoded_options[j++] = *saw_time;
  if (saw_libc)
    new_decoded_options[j++] = *saw_libc;

Listing 1.11-10: the re-emission (gcc/cp/g++spec.cc:430-443).

The move changes the link, and g++ prints no diagnostic for it: g++ -lm foo.o links foo.o -lstdc++ -lm. On a target where every library is a static archive, ld resolves symbols from left to right, so the order decides which symbols the link pulls in. The comment gives a sound reason, because libstdc++.a has undefined references into libm. The cost is that no g++ command line can put -lm before -lstdc++. If you need that order, link with gcc or ld and name the C++ runtime yourself.

When you pass no -lm, the else if branch of Listing 1.11-10 adds one. The branch is gated on need_math, which is (MATH_LIBRARY[0] != '\0') (gcc/cp/g++spec.cc:129). A port that folds the maths routines into libc defines MATH_LIBRARY "", so its link line has no -lm. Check MATH_LIBRARY before you conclude that a new target's link line is too short.

The saw_time slot for -lrt is dead code. saw_time is initialised to NULL (gcc/cp/g++spec.cc:118-119) and read in Listing 1.11-10, but no line in the file assigns it, because there is no TIMELIB bit to go with MATHLIB and WITHLIBC. It is unassigned at every release from 11.4.0 to 15.2.0, so exactly two of your options are ever moved: -lm and -lc.

One -### command shows the move. It prints each -l option of the commands the driver would run, in order, with any word that contains stdc:

$ g++ -### -lm -lz foo.o 2>&1 | tr ' ' '\n' | grep -E '^-l|stdc'

Listing 1.11-11: watch -lm come out after -lstdc++, and -lz stay where you put it.

In the output, -lz stays where you put it, and -lm comes after -lstdc++, where Listing 1.11-10 re-emits it.

-static-libstdc++ changes no path and no filename

-static-libstdc++ leaves the library name, the search order and every -L as they were, and wraps the one -lstdc++ in a pair of linker state changes. The GCC manual documents the contract under Link Options: the option makes g++ link libstdc++ statically, "without necessarily linking other libraries statically". The wrap is how g++ keeps that promise:

… -Wl,-Bstatic -lstdc++ -Wl,-Bdynamic -lm -lc

-Wl,-Bstatic switches ld to archive preference and -Wl,-Bdynamic switches it back, so the preference covers exactly one library. The hook emits the two halves around the -l, and Listing 1.11-12 is the opening half:

#ifdef HAVE_LD_STATIC_DYNAMIC
      if (library > 1 && !static_link)
	{
	  generate_option (OPT_Wl_, LD_STATIC_OPTION, 1, CL_DRIVER,
			   &new_decoded_options[j]);
	  j++;
	}
#endif

Listing 1.11-12: the opening half (gcc/cp/g++spec.cc:384-391), whose mirror image at :421-428 emits the closing LD_DYNAMIC_OPTION.

library > 1 is the 2 state, and !static_link skips the wrap under plain -static, where the whole link is archive-only already. The option that sets state 2 also deletes itself, on most targets:

	case OPT_static_libstdc__:
	  library = library >= 0 ? 2 : library;
#ifdef HAVE_LD_STATIC_DYNAMIC
	  /* Remove -static-libstdc++ from the command only if target supports
	     LD_STATIC_DYNAMIC.  When not supported, it is left in so that a
	     back-end target can use outfile substitution.  */
	  args[i] |= SKIPOPT;
#endif
	  break;

Listing 1.11-13: gcc/cp/g++spec.cc:235-243.

The library >= 0 guard keeps g++ -c -static-libstdc++ at -1, because -c got there first. The #ifdef means that on a target without HAVE_LD_STATIC_DYNAMIC the option is not deleted, so it survives into the specs for the port to act on. That conditional is why two targets disagree about whether the option appears in -v output.

-static-libstdc++ needs libstdc++.a in the same search path as the shared library, because the search does not change, only ld's preference between .a and .so. If you ship a cross toolchain with a shared-only libstdc++, the option gives you the shared library with no diagnostic, and the link succeeds.

On most targets the option itself does not appear on the link line, because the hook deleted it. Search -v output for Bstatic, not for -static-libstdc++:

$ g++ -### -static-libstdc++ foo.o 2>&1 | tr ' ' '\n' | grep -E 'Bstatic|Bdynamic|stdc'

Listing 1.11-14: the option is gone, and its effect is two -Wl, options.

The output shows -Bstatic before -lstdc++ and -Bdynamic after it, and no -static-libstdc++. On another linker the pair is spelled differently, because configure picks the spelling by target, in a case "$target" (gcc/configure.ac:4231-4250) followed by three AC_DEFINEs (:4253-4259):

ValueTarget
-Bstatic / -BdynamicGNU ld and Solaris (the default)
-bstatic / -bdynamicAIX
-aarchive_shared / -adefaultHP-UX (non-GNU ld)

LIBSTDCXX is the macro that names the library g++ injects, so a port can change it. Two options change the library for one command: -fcontracts adds -lstdc++exp in front of it, and -stdlib=libc++ replaces it with clang's runtime. Listing 1.11-15 gives the default of LIBSTDCXX and of the two macros next to it:

#ifndef LIBSTDCXX
#define LIBSTDCXX "stdc++"
#endif
#ifndef LIBSTDCXX_PROFILE
#define LIBSTDCXX_PROFILE LIBSTDCXX
#endif
#ifndef LIBSTDCXX_STATIC
#define LIBSTDCXX_STATIC NULL
#endif

Listing 1.11-15: gcc/cp/g++spec.cc:44-52.

-p and -pg set saw_profile_flag, and the hook then names LIBSTDCXX_PROFILE (gcc/cp/g++spec.cc:407-410). LIBSTDCXX_STATIC is not a replacement but an extra library, appended after the main one when the link is static (:413-419). An RTOS or bare-metal port uses it to add its own support archive. If a link line on an unusual target does not say -lstdc++, one of these three macros is why.

-fcontracts adds -lstdc++exp ahead of the main library (gcc/cp/g++spec.cc:378-383). Those lines run before the -Wl,-Bstatic of Listing 1.11-12, so -static-libstdc++ does not cover libstdc++exp.

The GCC manual documents -stdlib= under C++ Dialect Options: the option selects the headers and the runtime library, libstdc++ or libc++. -stdlib=libc++ switches to clang's library and emits -lc++ and -lc++abi (gcc/cp/g++spec.cc:392-406). The hook skips the ABI library when the port sets LIBCXXABI to NULL. The comment on that macro gives the case: a platform may forward the ABI library from libc++ or combine it some other way. The option exists only if GCC was configured for it (ENABLE_STDLIB_OPTION), which Chapter 1.12 covers.

added_libraries and the no input files check

added_libraries counts the -l options that the hook added, so that plain g++ with no arguments fails with no input files. Without the count, the driver would see the libraries that the hook had added, conclude that it had inputs, and attempt a link. The hook hands the count back through the third out-parameter of Listing 1.11-1, and the generic driver reads it once:

  if (n_infiles == added_libraries)
    fatal_error (input_location, "no input files");

Listing 1.11-16: gcc/gcc.cc:8970-8971.

That comparison is the only use of the count, and the reason lang_specific_driver has to report what it did as well as doing it.

Three things to carry away

g++ is the C driver plus one hook. lang_specific_driver rewrites the option array before the driver acts on any option.

Injection is the default, not the exception. An -l the hook does not recognise, or any input that is not a header, adds -lstdc++.

Your -lm and -lc move. The hook re-emits them after -lstdc++. On a target with a separate maths library it also adds a -lm you did not ask for.

Things that surprise people

gcc never injects anything. Link C++ objects with gcc and you get undefined std:: symbols. At link time that is the practical difference between the two drivers, not a different compiler or different code generation.

g++ -lz foo.o links the C++ runtime, even though nothing in it is C++.

Only -lm and -lc move. Every other option keeps its position.

-nostartfiles does not suppress -lstdc++. The spec guards and the C++ hook check two different lists of options.

Documentation coverage

The options are documented: -static-libstdc++ and -nostdlib++ under Link Options (gcc/doc/invoke.texi:19416, :19262), and -stdlib= under C++ Dialect Options (:3748). No manual documents the mechanism:

  • The injection's conditions have no texi node. The manual states only the outcome: g++ "automatically specifies linking against the C++ library" (gcc/doc/invoke.texi:2360-2362). It does not say under what conditions. The library state machine exists only as the source comment in Listing 1.11-2.
  • The -lfoo rule is undocumented. Linking any third-party library through g++ guarantees the C++ runtime.
  • The input-file rule is undocumented. It tests for header suffixes, not for a C++ source, and Listing 1.11-5 is the only statement of it.
  • The -lm and -lc reordering is undocumented. No manual says that g++ moves two of your options, and g++ prints no diagnostic when it does.
  • -static-libstdc++'s mechanism is undocumented. The manual describes the option, but not that it becomes -Wl,-Bstatic … -Wl,-Bdynamic and leaves the command line, nor the HAVE_LD_STATIC_DYNAMIC conditional that decides whether it leaves.

For the mechanism, the comments in g++spec.cc are the specification.

Next: Chapter 1.12, Which libstdc++, and which <vector>, the file that the injected -lstdc++ finds and the <vector> you compiled against.