1.1 What gcc foo.c runs: cc1, as and collect2

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

You type gcc hello.c, and an a.out appears. Somewhere in between, your C was turned into machine code, and the obvious assumption is that gcc did it.

It did not, because gcc compiles nothing. A driver is a program that works out which other programs to run, builds each one's command line and runs them in order, and gcc is a driver. Almost every "GCC can't find X" problem is a driver problem, and the driver prints what it did if you ask it.

-### and -v: printing the commands the driver runs

-### prints every command line the driver would run, fully expanded and shell-quoted, and then runs none of them. Its sibling -v prints the same command lines and runs them. -### is the flag to learn before any other. It turns "GCC is doing something weird" into a concrete argument list that you can read, diff against a working toolchain and paste back into a shell. The GCC manual documents both flags under Overall Options.

$ gcc -### hello.c

The output names three or four separate programs, not one. In the diagram below, each arrow is a real fork and exec:

   gcc hello.c
     │
     ├─► cc1        hello.c  →  /tmp/ccXXXXXX.s     the actual C compiler
     │                                              (cc1plus for C++)
     ├─► as         .s       →  hello.o             the assembler, from binutils
     │
     └─► collect2   hello.o  →  a.out               a wrapper that runs ld
           └─► ld

The temporary .s file between cc1 and as is real too, and this command shows the name that the driver invents for it:

$ gcc -### hello.c 2>&1 | grep -o '/tmp/cc[A-Za-z0-9]*\.s'

It prints a name of the form /tmp/ccXXXXXX.s, which you never chose. cc1 and as still agree on it, because the driver generated one name and substituted it into both command lines. Chapter 1.3 explains the mechanism, and until then the intermediate files between stages are the driver's bookkeeping, not yours.

Three flags stop the chain early, each at one boundary between stages, which is a quick way to check that the stages are separate. Overall Options documents all three:

FlagStops after
-Ethe preprocessor
-Scc1, leaving a .s
-cas, leaving a .o
(none)the link

Where cc1, as and collect2 live

GCC installs cc1, collect2 and its other internal programs in a private libexec directory, not on $PATH, and as and ld come from binutils. The driver does not search $PATH for cc1, and could not, so it keeps a search list of program directories of its own. That list and the directories in the table below are where to look when the driver cannot find a program.

ProgramWhat it isInstalled in
gcc, g++the driver$prefix/bin/
cc1, cc1plus, lto1the real compilers$prefix/libexec/gcc/<target>/<version>/
collect2, lto-wrapperGCC's own link-time helperssame libexec directory
as, ldbinutilsbinutils' install, or the tool directory

All four rows are host programs: they run on your machine, as processes. GCC's own internal programs go in libexec because they are private implementation binaries that still have to be exec'd. Putting the target and the release in the path lets several GCCs coexist. The install manual documents both of GCC's directories under Configuration: --bindir for the programs that users call, and --libexecdir for GCC's internal executables.

The driver's list of program directories is separate from its list of library directories, and one command prints both. The GCC manual documents that command under Developer Options:

$ gcc -print-search-dirs

In its output, the programs: line is the executable list and the libraries: line is the list that resolves crt1.o and -lfoo. Separate code builds the two lists, and Chapter 1.5 shows how to read them. There is no third line for headers, for a reason that Chapter 1.5 also covers.

default_compilers[]: command lines are spec strings, not C code

default_compilers[], the driver's table of compilers, holds strings, not code. Each string is a template in a small %-escape language that the driver expands at run time, so the argument lists that -### prints are not written in C anywhere. The GCC manual documents the language under Spec Files. Listing 1.1-1 is the entry for a .c file, and that one string constant is the whole of GCC's knowledge of how to compile C.

  {".c", "@c", 0, 0, 1},
  {"@c",
   /* cc1 has an integrated ISO C preprocessor.  We should invoke the
      external preprocessor if -save-temps is given.  */
     "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
      %{!E:%{!M:%{!MM:\
      ...
      %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
	  cc1 %(cpp_unique_options) %(cc1_options)}}}\
      %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},

Listing 1.1-1: the .c entry in default_compilers[] (gcc/gcc.cc:1454-1468). Abridged. The omitted middle handles -save-temps and rejects -traditional.

The literal word cc1 in Listing 1.1-1 tells the driver what to run, because the program is the first word of an expanded template, not the value of a variable. The template's last line, %{!fsyntax-only:%(invoke_as)}, pulls in a second template, invoke_as.

Three consequences of building command lines from templates matter already, although the language itself waits until Chapter 1.3:

  1. A target customises GCC by replacing a template, not by patching the driver. Two GCCs built from identical source for different targets can behave differently, because their target headers #define different templates.
  2. -nostdlib, -nostartfiles and -nodefaultlibs are not implemented in C at all. They are conditionals inside one template string, which is why they compose the way they do, and Chapter 1.10 reads them.
  3. You can replace those templates yourself, per invocation, with -specs=FILE, without rebuilding anything.

invoke_as: a newline in a spec starts the next program

invoke_as is the template that runs the assembler, and the .c template expands it unless -fsyntax-only is given, which is why the assembler runs at all. Inside a template, a newline ends one program's command line, and what follows it is another program to run. The step from cc1 to as in the diagram is therefore a newline in a string, not a loop over stages in the driver's C code.

static const char *invoke_as =
"%{!fwpa*:\
   %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
   %{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
  }";

Listing 1.1-2: invoke_as, the #else branch (gcc/gcc.cc:1313-1324). Targets that define AS_NEEDS_DASH_FOR_PIPED_INPUT take the first branch, which writes %|.s on the as line.

In Listing 1.1-2 the newline is the \n in |\n as, immediately before the as command. The | in front of it asks for a pipe, and the driver uses one only under -pipe. Overall Options documents that flag as using "pipes rather than temporary files" between the stages. Without -pipe the driver drops the |, runs cc1 to the end, and then runs as on the file that cc1 wrote (gcc.cc:6157-6166). Chapter 1.4 follows those files.

Why the driver runs collect2, not ld

On most targets the last program in the chain is not ld but collect2, a GCC program that then runs ld. collect2 has a job of its own at link time, and that job needs a compiler, which is why the driver has to tell it which compiler to use. The default linker name comes from one macro:

#ifndef LINKER_NAME
#define LINKER_NAME "collect2"
#endif

Listing 1.1-3: LINKER_NAME (gcc/gcc.cc:902-904).

collect2's own opening comment says what it is for: "Collect static initialization info into data structures that can be traversed by C++ initialization and finalization routines" (gcc/collect2.cc:1-2). Some object formats have no native mechanism for running constructors before main. On those platforms something has to scan the objects, build a table of constructor and destructor pointers, and get that table into the image. collect2 does that scan, generates a small C file containing the tables, and compiles it.

COLLECT_GCC: how collect2 and lto-wrapper find the same compiler

COLLECT_GCC and COLLECT_GCC_OPTIONS make the driver's link-time helpers run the same compiler as your command, with the same switches. lto-wrapper, GCC's other link-time helper, needs a compiler as collect2 does, because it re-runs code generation at link time for link-time optimisation, and it also needs your original options. If either helper took whichever gcc came first on $PATH, the second pass would run with a different prefix, sysroot and search paths, and on a cross toolchain possibly a different target.

The driver prevents that by putting the answers in the environment before it spawns anything. COLLECT_GCC holds the full pathname of the running driver, taken from argv[0]:

  obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);

Listing 1.1-4: exporting COLLECT_GCC (gcc/gcc.cc:8718).

COLLECT_GCC_OPTIONS holds every switch, each one single-quoted, so the second pass reconstructs the same paths. This is the whole reason -B, --sysroot and -L survive into the link step, and it is also why gcc -v output is full of COLLECT_* lines:

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

The COLLECT_* lines it prints are already shell-quoted, so they paste into a terminal. They are the quickest way to reproduce what collect2 was handed.

Without these variables the two helpers behave differently. lto-wrapper refuses to run, and Listing 1.1-5 is its check for COLLECT_GCC:

  collect_gcc = getenv ("COLLECT_GCC");
  if (!collect_gcc)
    fatal_error (input_location,
		 "environment variable %<COLLECT_GCC%> must be set");

Listing 1.1-5: lto-wrapper hard-errors (gcc/lto-wrapper.cc:1444-1448).

collect2 is more forgiving, and that makes it the dangerous half of the pair, because it picks a compiler name of its own:

  /* Determine the full path name of the C compiler to use.  */
  c_file_name = getenv ("COLLECT_GCC");
  if (c_file_name == 0)
    {
#ifdef CROSS_DIRECTORY_STRUCTURE
      c_file_name = concat (target_machine, "-gcc", NULL);
#else
      c_file_name = "gcc";
#endif
    }

Listing 1.1-6: collect2's fallback (gcc/collect2.cc:1142-1151).

As Listing 1.1-6 shows, a collect2 run without COLLECT_GCC falls back to <target>-gcc when GCC was built with CROSS_DIRECTORY_STRUCTURE and to plain gcc otherwise, with no diagnostic. On a cross toolchain that can pick up a different compiler with different startfile and sysroot paths, and the only symptom is a link that resolves the wrong crtbegin.o. Chapter 1.9 covers the whole environment channel.

When collect2 is missing, the driver runs ld

When the driver cannot find collect2, it runs ld in its place, with no diagnostic. On a normal Linux toolchain collect2 runs ld, so ld never appears in the driver's output. When you grep -### output for the link line, grep for collect2, not for ld. Listing 1.1-7 is the fallback:

	  /* We'll use ld if we can't find collect2.  */
	  if (! strcmp (linker_name_spec, "collect2"))
	    {
	      char *s = find_a_program ("collect2");
	      if (s == NULL)
		set_static_spec_shared (&linker_name_spec, "ld");
	    }

Listing 1.1-7: the collect2-to-ld fallback (gcc/gcc.cc:9243-9249).

gcc and g++ are the same program

gcc and g++ are not two compilers but the same driver code, with one extra hook compiled in. The hook, lang_specific_driver, runs on the decoded command line before anything has acted on it, so it can insert, delete and reorder options. Those edits are the whole practical difference between the two commands at link time, and Listing 1.1-8 is the call:

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

Listing 1.1-8: the language hook (gcc/gcc.cc:4860-4862).

g++'s implementation does exactly two things: it makes .c files compile as C++, and it appends the C++ runtime libraries to your link. On the way, it moves your own -lm and -lc, with no diagnostic. Link C++ objects with gcc, and you get undefined std:: symbols and no other change. The GCC manual documents the two effects under Invoking G++, but none of the hook's details, so Chapter 1.11 takes the hook apart.

When something links wrong, run five driver commands in order and stop at the first surprise. Each asks the driver one question: whether your flag reaches the linker, where it searches, which copy of a file wins, whether a sysroot is in play and which ABI variant you get.

$ gcc -### foo.c                       # is the flag you passed even reaching the linker?
$ gcc -print-search-dirs               # is the directory you expect in `libraries:`?
$ gcc -print-file-name=libfoo.a        # which copy of it wins?
$ gcc -print-sysroot                   # is a sysroot in play at all?
$ gcc -print-multi-directory           # are you getting the right ABI variant?

-print-file-name walks the same list the linker is given, so its answer is the file the link would pick. When the file is not found at all, it prints your argument back unchanged, which makes it the quickest diagnosis of a missing file. Chapter 1.5 explains why it works that way.

Three things to carry away

gcc compiles nothing. It decides which programs to run, builds each one's command line, and runs them. -### shows every command line and runs none.

The command lines are templates, not C code. A target changes what the driver runs by replacing a template, and so can you, with -specs=FILE.

The driver hands its own identity to its children. COLLECT_GCC and COLLECT_GCC_OPTIONS make collect2 and lto-wrapper re-run the same compiler with the same switches.

Things that surprise people

There is no gcc/specs.cc, and there never has been. The spec language lives in gcc/gcc.cc, where the interpreter is a function called do_spec_1. A great deal of secondhand documentation names gcc/specs.cc anyway.

Documentation coverage

The observation tools are documented: -### and -v are in Overall Options (gcc/doc/invoke.texi:1549), the -print-* family is in Developer Options (:20326), and the spec language has its own node, Spec Files (:37290). The internals manual's Collect2 node (gcc/doc/collect2.texi:5) documents how collect2 finds the real ld.

What is not documented:

  • The COLLECT_GCC channel, from the driver's side. Neither manual mentions the variable.
  • collect2's fallback to <target>-gcc or to gcc, when COLLECT_GCC is unset.

Next: Chapter 1.2, Build, host and target: which files --sysroot moves, the vocabulary the rest of Part I is written in: three machine names, and the difference between a program that runs and an object that only ever gets linked.