gcc main.c -o main looks like one action and is four. Knowing them by name is what turns a confusing error message into an obvious one, because each stage fails differently.
Preprocessing is text substitution. It expands #include by pasting the whole header in, replaces every #define, and strips comments. Its output is still C, and you can read it with gcc -E. An error here is a missing header or a macro that expanded into nonsense. Compiling turns that expanded source into assembly for your processor, and this is the stage that reports syntax errors and type mismatches. Assembling turns the assembly into machine code in an object file - one per source file, with unresolved references left as placeholders. Linking joins the object files and the libraries, resolving those placeholders into real addresses.
The distinction that saves the most time is between a compiler error and a linker error. "Undefined reference to sqrt" is not a missing include - the header told the compiler the function exists, and the linker then could not find its body, which is why maths functions need -lm. A missing declaration is a compiler error; a missing definition is a linker error.
Always compile with -Wall -Wextra. C's defaults are permissive for historical reasons, and most of what those flags report is a real bug.
/* main.c - the anatomy of a C program. */
#include <stdio.h> /* the preprocessor pastes this whole file in */
#define GREETING "Hello" /* and replaces every GREETING below */
int main(void) /* void, not () - see the note below */
{
printf("%s, C!\n", GREETING);
return 0; /* 0 means success, to whatever ran this */
}
/* The four stages, run one at a time so you can see each output:
gcc -E main.c -o main.i # 1. preprocess - still C, now enormous
gcc -S main.i -o main.s # 2. compile - assembly
gcc -c main.s -o main.o # 3. assemble - machine code, unresolved
gcc main.o -o main # 4. link - a program
All four at once, which is what you will normally type:
gcc -Wall -Wextra -g main.c -o main
-Wall -Wextra turn on the warnings. Most of them are real bugs.
-g keep the debug symbols, so gdb can name your lines.
"undefined reference to sqrt" is a LINKER error, not a missing
include: math.h declared it, and the linker could not find the body.
gcc main.c -o main -lm
*/
/* int main(void) rather than int main(). In C, empty parentheses mean
"unspecified arguments", not "no arguments" - void says no. */