Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 135 ยท Getting Started

How C Works: Compiling and Linking

See how C source code becomes a program. Learn the preprocessor, compiler, assembler and linker, object files, C standards from C89 to C23, and warning flags.

A C program starts as plain text that you write, but your processor can only run machine code: binary instructions specific to its architecture. Turning one into the other is the job of a toolchain, a chain of programs that each do one step. When you press Run in our editor, that whole chain runs on our server in a fraction of a second.

You can write C for years without thinking about these steps, until something goes wrong. Then knowing whether a message came from the preprocessor, the compiler or the linker tells you immediately where to look. This lesson walks through the pipeline, the C standards, compiler warnings, and how to set up a compiler on your own computer.

The four stages

Building a C program happens in four stages. Most of the time a single command such as gcc main.c -o main runs all of them for you, but each one does a distinct job:

Stage Input Output What it does
1. Preprocessor main.c translation unit (text) Handles lines starting with #: pastes in headers, expands macros, removes comments
2. Compiler preprocessed C assembly code (main.s) Checks syntax and types, optimizes, translates C into assembly for the target CPU
3. Assembler assembly object file (main.o) Turns assembly into machine code, leaving holes for things defined elsewhere
4. Linker object files + libraries executable (main or main.exe) Connects calls to the functions they refer to and produces the final program

Here's how you could run each stage separately with GCC, to see the intermediate files:

Terminal
gcc -E main.c -o main.i    # 1. preprocess only
gcc -S main.i -o main.s    # 2. compile to assembly
gcc -c main.s -o main.o    # 3. assemble to an object file
gcc main.o -o main         # 4. link into an executable
./main                     # run it (main.exe on Windows)

In daily work you just write gcc main.c -o main, and GCC deletes the intermediate files when it's done.

Stage 1: the preprocessor

The preprocessor is a text-processing step that runs before real compilation. It only cares about directives, lines that start with #:

  • #include <stdio.h> is replaced by the entire contents of the stdio.h header file. That's how printf gets declared in your file.
  • #define NAME value creates a macro: every later NAME in the code is replaced by value.
  • #if, #ifdef and friends include or skip code depending on conditions.

The preprocessor also defines some macros for you. __FILE__ and __LINE__ become the current file name and line number, and __STDC_VERSION__ tells you which C standard the compiler is using:

C Macros the preprocessor provides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

By the time the compiler proper sees this code, GREETING has become "Hello from a macro", SQUARE_OF_SEVEN has become (7 * 7) and __LINE__ has become 9. The value 202311 means the November 2023 standard: C23. You'll learn about macros in depth in the Preprocessor chapter.

Note: Because #include literally pastes text, a tiny program with one #include <stdio.h> becomes hundreds of lines after preprocessing. Run gcc -E main.c on your own machine to see it.

Stage 2: the compiler

The compiler is where your code is understood. It parses the preprocessed text, checks that it follows C's grammar, checks that types fit together (for example that you don't pass text where a number is required), and then translates it into assembly language for the target processor. Along the way it optimizes: with -O1 or -O2, GCC removes useless work, keeps values in registers and simplifies calculations.

Most of the error messages you'll see come from this stage: a missing semicolon, an unknown variable name, a type mismatch. The compiler also gives warnings, which are messages about code that is legal C but probably wrong.

Stage 3: the assembler and object files

The assembler turns assembly text into machine code and writes an object file (.o on Linux and macOS, .obj with Microsoft's compiler). An object file holds the machine code for the functions in one source file, plus a symbol table listing what the file defines (for example main) and what it needs from elsewhere (for example printf).

The object file isn't runnable yet. Its call to printf is a placeholder that says "the address of printf goes here", because printf lives in the C standard library, not in your file.

Stage 4: the linker

The linker takes one or more object files plus libraries and stitches them together. For each placeholder, it finds the matching definition and fills in its address. The C standard library (libc) is linked automatically; other libraries are added with flags such as -lm for the math library.

Large programs are split into many .c files. Each one is compiled into its own object file, separately, and the linker combines them:

Terminal
gcc -c main.c          # creates main.o
gcc -c geometry.c      # creates geometry.o
gcc main.o geometry.o -o app

The advantage: when you change geometry.c, only that file has to be recompiled. Build tools like make and CMake automate exactly this.

If the linker can't find a definition, you get a linker error. It looks different from a compiler error, because the compiler was happy. Run this example, which fails on purpose:

C A linker error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The line int add_tax(int price); is a declaration: it promises the compiler that a function with this name and signature exists somewhere. The compiler trusts the promise and compiles the call. The linker then looks for the actual function body, finds nothing, and stops with a message like:

TEXT
undefined reference to `add_tax'
collect2: error: ld returned 1 exit status

ld is the linker program. When you see "undefined reference", ask: did I forget to write the function, misspell its name, forget to compile one of my .c files, or forget a library flag like -lm? Declarations, Prototypes and Headers explains declarations properly.

Compilers you can use

Three compiler families dominate:

  • GCC (GNU Compiler Collection): the standard compiler on Linux, also available on Windows through MSYS2 or WSL. This site uses GCC 15.2.
  • Clang (LLVM): the default on macOS (installed with Xcode's command-line tools), also common on Linux and Windows. It accepts almost the same flags as GCC and is known for clear error messages.
  • MSVC (Microsoft Visual C++): the compiler in Visual Studio on Windows. It supports C11 and C17 well; its support for newer C features has historically lagged behind GCC and Clang.

Embedded developers also use vendor compilers and cross-compilers, which run on your PC but produce code for a different processor, such as an ARM microcontroller.

The C standards

C is defined by an ISO standard, revised every few years. Compilers let you choose which version to follow:

Standard Year Highlights
C89 / C90 1989/1990 The first standard ("ANSI C"): function prototypes, const, void
C99 1999 // comments, long long, <stdbool.h>, <stdint.h>, declarations anywhere, for (int i = 0; ...), variable-length arrays
C11 2011 Threads (<threads.h>), atomics, _Generic, _Static_assert, anonymous structs, removal of gets
C17 2018 Bug-fix release, no new features
C23 2024 bool/true/false keywords, nullptr, constexpr, typeof, [[attributes]], 0b1010 binary literals, 1'000'000 digit separators, #embed

With GCC and Clang you select a standard with -std=: -std=c99, -std=c11, -std=c17 or -std=c23. The -std=gnu17 style adds GNU extensions on top. GCC 8 to 14 default to gnu17 and GCC 15 switched to gnu23, while other compilers have their own defaults, so it's good practice to always say which standard you mean.

You can check the standard from inside your code. This example also shows the compiler version, using macros that GCC and Clang define:

C Which compiler and standard?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The #if lines are evaluated by the preprocessor, so only one of the three printf lines even reaches the compiler. Try this on your own computer with -std=c17 and watch the first line change.

Warnings and flags

Warnings are the cheapest bug detector you'll ever have. GCC and Clang print very few by default, so experienced C programmers always turn more on:

Flag Meaning
-Wall Enables a large set of common warnings (despite the name, not all of them)
-Wextra Adds more useful warnings on top of -Wall
-Wpedantic Warns about anything that isn't strict standard C
-Werror Turns every warning into an error, so the build fails
-std=c17 Chooses the language standard
-O0, -O1, -O2, -O3 Optimization level (none to aggressive)
-g Adds debugging information for tools like gdb
-o name Names the output file
-lm Links the math library (needed for sqrt, pow and friends on Linux)

Our editors compile with gcc -std=c23 -O1 -Wall -Wextra -pthread main.c -lm. Here is code that compiles but deserves a closer look:

C Warnings point at bugs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program runs and prints I have 5 apples, but GCC reports two warnings: unused variable 'unused_total' (-Wunused-variable) and too many arguments for format (-Wformat-extra-args), because the format string has one %d but you passed two numbers. Neither is fatal here, but both are signs that the code doesn't do what its author meant. Make it a habit to fix every warning.

Tip: A good everyday command on your own machine is gcc -std=c17 -Wall -Wextra -Wpedantic -g main.c -o main. While debugging memory bugs, add -fsanitize=address,undefined: the program then reports out-of-bounds accesses and other undefined behavior the moment they happen.

Installing a compiler

You can follow this whole course in the browser, but sooner or later you'll want C on your own machine:

  • Linux: install GCC from your package manager, for example sudo apt install build-essential on Debian/Ubuntu or sudo dnf install gcc on Fedora.
  • macOS: run xcode-select --install in Terminal. This installs Clang; the gcc command on macOS is actually Clang.
  • Windows: install Visual Studio (with "Desktop development with C++", which includes the C compiler), or install MSYS2 and then GCC with pacman -S mingw-w64-ucrt-x86_64-gcc. WSL (Windows Subsystem for Linux) lets you use the Linux instructions too.

Then compile and run from a terminal:

Terminal
gcc -std=c17 -Wall -Wextra main.c -o main
./main

Any editor works; Visual Studio Code with the C/C++ extension, CLion and Visual Studio are popular choices.

Interpreted versus compiled

Languages like Python and JavaScript are usually run by an interpreter or a just-in-time compiler that sits between your code and the machine. C has no such layer: the executable you get is machine code that the operating system loads and runs directly. That's why C programs start instantly and use little memory, and also why a C executable built for Linux on x86-64 won't run on a Mac with an ARM chip. To run there, you recompile the same source with a compiler for that platform. Writing portable C means writing code that compiles and behaves the same everywhere, which is why this course keeps pointing out what the standard guarantees and what it leaves to each implementation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which stage replaces #include <stdio.h> with the contents of the header?

    Lines starting with # are handled by the preprocessor before compilation. #include pastes in the header's text.
  2. 2. A build fails with "undefined reference to area". Which stage reported it?

    The compiler accepted the call because area was declared, but the linker couldn't find a definition of the function in any object file or library.
  3. 3. What is in an object file (.o)?

    An object file holds compiled machine code for one translation unit. References to functions in other files are left as placeholders for the linker.
  4. 4. What does __STDC_VERSION__ equal when compiling as C23?

    C23's value is 202311L. C99 is 199901L, C11 is 201112L and C17 is 201710L.
  5. 5. Your program compiles with a warning and seems to work. What should you do?

    Warnings mark code that is legal but suspicious. Fixing them is the cheapest way to catch bugs before they bite.

Summary

  • Building C has four stages: preprocessor (# lines), compiler (C to assembly), assembler (object files) and linker (one executable).
  • #include pastes header text; #define creates macros; __FILE__, __LINE__ and __STDC_VERSION__ are predefined.
  • Each .c file compiles to its own object file; the linker joins them and the libraries, and reports "undefined reference" when a definition is missing.
  • GCC, Clang and MSVC are the main compilers; choose a standard with -std=c17 or -std=c23.
  • Turn on warnings (-Wall -Wextra) and fix every one of them.
  • Our editors compile with gcc -std=c23 -O1 -Wall -Wextra -pthread main.c -lm.

Next: C Syntax, where you'll learn the rules every C program follows.