1.9 How GCC_EXEC_PREFIX and LIBRARY_PATH move the search paths

GCC 15.2.0. To run the commands: an installed compiler.

The build works on your machine and fails in CI. The source is the same, the compiler version is the same, and you have checked the command line three times.

Check the environment next, because the variables that move GCC's search paths do not appear on any command line you can read. They fall into three groups, by who sets them and who reads them. You set the first group to move the driver's search lists. You set the second group too, but the driver never reads it and cc1 does. The driver sets the third group, so that its own subprocesses agree with it:

GroupSet byRead byVariables
Inyouthe driverGCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH
Past the driveryoucc1CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH
Outthe driverits childrenCOLLECT_GCC, COLLECT_GCC_OPTIONS, COLLECT_LTO_WRAPPER, COLLECT_AS_OPTIONS

This chapter assumes Chapter 1.1 for collect2, lto-wrapper and COLLECT_GCC, Chapter 1.3 for spec directives such as %<, and Chapter 1.4 for -dumpdir. It also assumes Chapter 1.5 and Chapter 1.8, because the first two groups feed the lists those chapters build: the driver's prefix lists and cc1's include chains.

Driver variables: GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH, LPATH

The driver reads four variables, GCC_EXEC_PREFIX, COMPILER_PATH, LIBRARY_PATH and LPATH, and adds their directories to the search lists that -B and the compiled-in defaults also fill. They are the first suspects when the driver finds a different program or library on two machines. Each one feeds a different part of the lists, and a cross compiler ignores two of them:

VariableFeedsWorks on a cross compiler?
GCC_EXEC_PREFIXprograms and libraries, plus header searchyes
COMPILER_PATHprograms and headersyes
LIBRARY_PATHlibrariesno, native only
LPATHas LIBRARY_PATH, legacyno, native only

Listing 1.5-3 in Chapter 1.5 settles their priority. Its enum has two values, and GCC_EXEC_PREFIX, COMPILER_PATH and LIBRARY_PATH all land at the lower one, PREFIX_PRIORITY_LAST. -B therefore beats the environment, the environment beats the compiled-in defaults, and nothing can sort before a -B. The GCC manual documents the first three variables, and that order, under Environment Variables. It does not mention LPATH.

LIBRARY_PATH and LPATH: ignored by a cross compiler

A cross compiler ignores LIBRARY_PATH and LPATH, because the driver reads each of them only when it was built as a native compiler. If LIBRARY_PATH has no effect on your arm-linux-gnueabihf-gcc, one clause of the driver is the reason:

  temp = env.get (LIBRARY_PATH_ENV);
  if (temp && *cross_compile == '0')

Listing 1.9-1: the native-only guard (gcc/gcc.cc:4923-4924). LPATH gets the same treatment at :4956-4957.

*cross_compile == '0' means "this is a native compiler", so a cross compiler skips the variable and prints no diagnostic. Use -B or -L instead. The manual's LIBRARY_PATH entry states the same condition in one clause: "When configured as a native compiler".

GCC_EXEC_PREFIX and COMPILER_PATH have no such guard, so they work on a cross compiler (gcc.cc:4889). The name in Listing 1.9-1 is LIBRARY_PATH_ENV, a macro rather than a literal, so a port can rename the variable, and some do (gcc.cc:209-211).

GCC_EXEC_PREFIX: relocation for programs, libraries and headers

GCC_EXEC_PREFIX is the relocation mechanism of Chapter 1.5, seen from outside the driver. Its documented default is $prefix/lib/gcc/, but when it is unset, the driver derives it from argv[0] and exports it anyway, as Listing 1.5-4 shows. Setting it by hand only pre-empts that computation. Whoever sets it, the variable does three things:

      set_std_prefix (gcc_exec_prefix, len);
      add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
		  PREFIX_PRIORITY_LAST, 0, 0);
      add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
		  PREFIX_PRIORITY_LAST, 0, 0);

Listing 1.9-2: what GCC_EXEC_PREFIX feeds (gcc/gcc.cc:4879-4884).

The two add_prefix calls put the relocated prefixes on exec_prefixes and startfile_prefixes, the program and library search lists. The set_std_prefix call is the one that is easy to miss, because it moves header search too. It tells gcc/prefix.cc what to substitute for the configure-time prefix in compiled-in directory names, and the manual's GCC_EXEC_PREFIX entry documents that substitution. That is how a relocated toolchain finds its own <stdint.h>, and Chapter 1.8 shows the code that consumes the substitution.

Two smaller behaviours come with the variable. A small block recognises a trailing /lib/gcc/ and shortens the length before use, so pointing the variable at either $prefix/ or $prefix/lib/gcc/ behaves the same (gcc.cc:4864-4877). The variable relocates the sysroot too, but only if the toolchain was configured with the sysroot inside $exec_prefix (gcc.cc:5542-5559), the condition that Chapter 1.5 covers.

-no-canonical-prefixes changes which function computes the relative prefix, so a driver reached through a symlink resolves to the symlink's directory rather than to the real one. It belongs with GCC_EXEC_PREFIX because it changes the same relocation computation. The GCC manual documents the option under Directory Options:

      if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
	{
	  get_relative_prefix = make_relative_prefix_ignore_links;
	  break;
	}

Listing 1.9-3: -no-canonical-prefixes (gcc/gcc.cc:4807-4816).

The comment above this code explains why the option is handled early, before normal option processing: the prefixes it affects are needed to build the default search paths. It is the only option in the driver treated that way.

Checking the driver variables with env -u and -print-search-dirs

Comparing gcc -print-search-dirs with and without GCC_EXEC_PREFIX, COMPILER_PATH and LIBRARY_PATH shows whether the environment moves a search list. Run the pair first whenever a toolchain behaves differently in two places, such as your machine and CI:

$ gcc -print-search-dirs

$ env -u GCC_EXEC_PREFIX -u COMPILER_PATH \
      -u LIBRARY_PATH gcc -print-search-dirs

If the two outputs differ, one of the three variables is set in that environment, and the programs: or libraries: line that changed shows which list it moved.

The driver rewrites COMPILER_PATH and LIBRARY_PATH for collect2

Before it runs collect2 or ld, the driver overwrites COMPILER_PATH and LIBRARY_PATH with its own final prefix lists. A child process therefore sees the resolved lists, including everything that -B and the compiled-in defaults contributed, and not the value the shell exported. The rewrite takes two calls:

      /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
	 for collect.  */
      putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
      putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);

Listing 1.9-4: propagation to subprocesses (gcc/gcc.cc:9275-9278).

Reading LIBRARY_PATH inside a build script that GCC invoked therefore reports the driver's lists, not the shell's value. This shows up in configure scripts and in Makefiles driven from a compiler wrapper, where the value looks like a user setting and is not.

CPATH and the *_INCLUDE_PATH variables: read by cc1, not the driver

CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH and OBJC_INCLUDE_PATH move header search, but nothing in gcc/gcc.cc reads them. They reach cc1 in the environment that the driver passes on, so no driver option shows their effect. cc1 reads them while it builds its include chains:

  /* CPATH and language-dependent environment variables may add to the
     include chain.  */
  add_env_var_paths ("CPATH", INC_BRACKET);
  add_env_var_paths (lang_env_vars[idx], INC_SYSTEM);

Listing 1.9-5: the header variables (gcc/incpath.cc:505-508), in register_include_chains. The table of language variables is at :494-496.

CPATH joins the bracket chain, where -I directories go. The language variable joins the system chain, where -isystem directories go, and idx selects it by the language cc1 is compiling. Both calls come before GCC's own directories and the system's are added, so both variables win over the defaults. The same Environment Variables node documents this mapping to -I and -isystem, and the empty-element rule, from gcc/doc/cppenv.texi.

Two consequences follow for debugging. -print-search-dirs cannot show these variables, and the env -u diff of the driver variables does not unset them. Ask cc1 instead: gcc -v -E - < /dev/null prints them with the rest of the header search list. An empty element means the current directory (gcc/incpath.cc:115-116), so a trailing : that a shell script left on CPATH puts . on the header search list.

COLLECT_* variables: how collect2 and lto-wrapper re-enter the driver

The COLLECT_* variables flow the other way: the driver sets them and its children read them. Two of those children re-enter the driver, as Chapter 1.1 describes, so they need to know which driver to run and with which switches. collect2 must compile the constructor tables it generates, and lto-wrapper must re-run code generation at link time with the original options. COLLECT_GCC and COLLECT_GCC_OPTIONS carry those two answers, so when a link goes wrong they show what the inner driver was told.

COLLECT_GCC: the path of the outer driver

COLLECT_GCC holds the full pathname of the running driver, taken from argv[0] rather than from progname. The comment above the code gives the reason:

/* Set up to remember the pathname of gcc and any options
   needed for collect.  We use argv[0] instead of progname because
   we need the complete pathname.  */

void
driver::putenv_COLLECT_GCC (const char *argv0) const
{
  obstack_init (&collect_obstack);
  obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
  obstack_grow (&collect_obstack, argv0, strlen (argv0) + 1);

Listing 1.9-6: exporting COLLECT_GCC (gcc/gcc.cc:8710-8721).

progname would give gcc. argv[0] gives the path that was invoked, which is the only thing that identifies this installation among several on one machine.

lto-wrapper and collect2, the two consumers of COLLECT_GCC, disagree about what to do when it is missing. Chapter 1.1 shows both code paths (lto-wrapper.cc:1444-1448 and collect2.cc:1142-1151):

ConsumerBehaviour when unset
lto-wrapperhard error: "environment variable COLLECT_GCC must be set"
collect2falls back to <target>-gcc in a cross-directory build, otherwise to gcc

The collect2 fallback is the dangerous one on a cross toolchain. A collect2 invoked without COLLECT_GCC can pick up a different compiler, and with it a different sysroot, different startfile prefixes and a different crtbegin.o. The link succeeds and the binary is wrong, with no diagnostic.

COLLECT_GCC_OPTIONS: the outer driver's switches, quoted

COLLECT_GCC_OPTIONS holds every switch of the outer driver, and each of its arguments, single-quoted one by one. A value looks like this:

COLLECT_GCC_OPTIONS='-B' '/opt/alt/' '--sysroot=/arm-rootfs' '-O2' '-dumpdir' 'a-'

The function that builds it states its contract in its comment:

/* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
   and place that in the environment.  */

static void
set_collect_gcc_options (void)

Listing 1.9-7: set_collect_gcc_options (gcc/gcc.cc:5610-5614).

The variable is therefore not the command line as typed, because the driver leaves out the switches that a %<S directive removed. %<S is the spec directive that removes the switch -S (Chapter 1.3), and the loop that fills the variable skips such switches explicitly:

      /* Ignore elided switches.  */
      if ((switches[i].live_cond
	   & (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
	  == SWITCH_IGNORE)
	continue;

Listing 1.9-8: %<S filtering (gcc/gcc.cc:5634-5638).

The driver rebuilds the variable before every subprocess rather than taking a snapshot at startup, so each value reflects the spec state at that moment (gcc.cc:5841 and :6169). It also holds switches that nobody typed, such as -dumpdir and other options synthesised along the way. A COLLECT_GCC_OPTIONS line therefore holds switches that are not in the command line you typed. Embedded single quotes are escaped as '\'' in the loop that follows the lines of Listing 1.9-7, which makes the whole line safe to paste into a shell.

COLLECT_GCC_OPTIONS carries path flags into the inner driver

COLLECT_GCC_OPTIONS is what lets path flags survive the recursion into collect2 and back. A -B, --sysroot or -L on the command line lands in the variable. When collect2 re-invokes the driver with those options, the inner driver therefore rebuilds the same prefix lists and the same sysroot as the outer one. Together with the rewrite of COMPILER_PATH and LIBRARY_PATH in Listing 1.9-4, it keeps every process in the tree in agreement about where files live. Without it, a -B would apply to the compile and not to the link, with no diagnostic.

COLLECT_LTO_WRAPPER, COLLECT_AS_OPTIONS and COLLECT_NO_DEMANGLE

Three more variables complete the family. The driver sets COLLECT_LTO_WRAPPER and COLLECT_AS_OPTIONS for its children, and COLLECT_NO_DEMANGLE is the only member of the family that you would ever set deliberately:

VariablePurposeSet at
COLLECT_LTO_WRAPPERpath to lto-wrappergcc.cc:8726-8745
COLLECT_AS_OPTIONSaccumulated -Xassembler / -Wa, optionsgcc.cc:6094-6112
COLLECT_NO_DEMANGLEsuppresses symbol demangling in collect2you, by hand

COLLECT_NO_DEMANGLE is the odd one out because it is an input. collect2 reads it (collect2.cc:895) and then re-exports it, so that a nested invocation inherits it (:898).

collect2 also reads COLLECT_LTO_WRAPPER, and stops with an error if it is absent, but only when collect2 handles link-time optimisation itself. That happens when the link runs without the linker plugin, so collect2 sees no -plugin, and an object holds IR (collect2.cc:597-614). IR is GCC's intermediate representation, which cc1 writes into the object file under -flto. Chapter 1.13 explains both routes, with the linker plugin and without it.

Checking the COLLECT_* variables with gcc -v

gcc -v prints every variable that the driver sets, because the function that sets them echoes each one under -v. That makes -v the quickest way to see what collect2 and lto-wrapper were handed:

void
env_manager::xput (const char *string)
{
  if (m_debug)
    fprintf (stderr, "env_manager::xput (%s)\n", string);
  if (verbose_flag)
    fnotice (stderr, "%s\n", string);

Listing 1.9-9: why -v echoes the environment (gcc/gcc.cc:126-132).

The verbose_flag test is the echo. Filtering the -v output of a link for lines that start with COLLECT_ shows the variables the driver set:

$ gcc -v hello.c 2>&1 | grep '^COLLECT_'

The first line is COLLECT_GCC=, followed by COLLECT_LTO_WRAPPER= when the command links and the driver finds lto-wrapper (gcc.cc:8730-8733). A fresh COLLECT_GCC_OPTIONS= line then comes immediately before every subprocess, one for each rebuild of the variable. The lines are already shell-quoted, so they paste into a terminal and reproduce what collect2 was handed.

Setting COLLECT_GCC or COLLECT_GCC_OPTIONS yourself has an effect only when you run collect2 or lto-wrapper directly, which can help when debugging a link. Before a normal gcc run, exporting them accomplishes nothing, because the driver overwrites both before it spawns anything.

Three things to carry away

-B outranks GCC_EXEC_PREFIX, COMPILER_PATH and LIBRARY_PATH. The prefix lists have two priority levels, and -B has the higher one.

LIBRARY_PATH does nothing on a cross compiler. One *cross_compile == '0' guard skips it, and the driver prints no diagnostic.

COLLECT_GCC and COLLECT_GCC_OPTIONS make path flags survive the recursion into collect2. Without them, a collect2 can use the wrong compiler, with no diagnostic.

Documentation coverage

GCC_EXEC_PREFIX, COMPILER_PATH and LIBRARY_PATH are documented, in the Environment Variables node (gcc/doc/invoke.texi:37984, with the individual items at :38057, :38092 and :38099). The header variables are in the same node, from gcc/doc/cppenv.texi (included at invoke.texi:38155), including the empty-element rule.

What is not documented:

  • That the driver never reads the header variables, so no driver option shows their effect.
  • The COLLECT_* family that the driver exports. The Environment Variables node covers what you may set, and the outward channel is in the source only.
  • collect2's fallback to <target>-gcc or gcc when COLLECT_GCC is unset.
  • That the driver overwrites COMPILER_PATH and LIBRARY_PATH before spawning the linker, so their values inside a child process are the driver's, not yours.
  • That switches removed by %<S are absent from COLLECT_GCC_OPTIONS.

Next: Chapter 1.10, Turning the runtime off: -nostdlib and -ffreestanding, what -nostdlib and its relatives take off the link line, and what you then owe.