From source to executable

A C program's build chain: preprocessor, compilation, assembly, linking and loading, the .c, .h, .i, .s and .o files, static and dynamic libraries, gcc's -E, -S, -c, -o and -l options, and the difference between compiled, interpreted and virtual machine.

  • 30 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Compilation pipeline: what is it?

    Show the answer

    The series of tools that turn a C program into an executable: preprocessor, compiler, assembler, linker.

    The gcc command chains them, but each stage has its own intermediate file and its own errors: knowing which one failed guides the diagnosis.

  • Which file does the command gcc -c main.c produce?

    • main.o
    • a.out
    • main.s
    • main.i
    Show the answer

    main.o

    -c compiles and assembles without linking: the result is the object file main.o. a.out is the default name of a complete executable; main.s comes from -S, and the preprocessed text from -E.

  • gcc options stop the chain at a given stage: -E after the …, -S after compilation, -c after ….

    Show the answer

    gcc options stop the chain at a given stage: -E after the preprocessor, -S after compilation, -c after assembly.

    -S leaves a .s file in assembly language, -c a .o file. Without these options, gcc goes all the way to the executable.

  • Preprocessor: what is it?

    Show the answer

    The first stage, purely textual: it replaces #include lines with the files' content, expands #define and strips comments.

    It does not understand C: gcc -E main.c shows the text it hands to the compiler, already several hundred lines for a single #include <stdio.h>.

  • A program that calls sqrt compiles, but linking prints undefined reference to 'sqrt'. Which fix is needed?

    • Add #include <math.h> at the top of the file
    • Add the -E option to expand macros
    • Recompile with -c to regenerate the object file
    • Add -lm at the end of the gcc command
    Show the answer

    Add -lm at the end of the gcc command

    If math.h were missing, the compiler would be the one to report it (implicit declaration of sqrt). Here the declaration is known; it is the definition, in the maths library, that the linker cannot find. -lm goes after the source files: placed before them, the linker may skip the library and the error remains.