gcc (the GNU C compiler) turns C source code into a program the CPU can run. clang is another compiler that accepts the same commands.
gcc hello.c -o hello # compile hello.c into the program hello
./hello # run it
Without -o, the program is called a.out (a.exe on Windows). For C++, use g++ in the same way.
The flags you should always use
| Flag | What it does |
|---|---|
-Wall -Wextra | turn on warnings about code that is legal but probably wrong |
-std=c11 | follow the C11 standard (-std=c++17 for C++) |
-g | keep line numbers and variable names for the debugger |
-O2 | optimize: a faster program, but harder to debug |
-o name | name the output file |
-lm | link the math library (needed for sqrt on some systems) |
A good everyday command:
gcc -Wall -Wextra -std=c11 -g main.c -o main
Why warnings matter
#include <stdio.h>
int main(void) {
int stock = 3;
if (stock = 0) {
printf("sold out\n");
} else {
printf("in stock: %d\n", stock);
}
return 0;
}stock = 0 is an assignment, not a comparison: it sets stock to 0, and the if sees 0, which is false. It is legal C, so plain gcc compiles it without a word, and the program prints "in stock: 0". With -Wall, gcc warns you:
warning.c:5:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
5 | if (stock = 0) {
| ^~~~~
Press Visualize: StepVioz is stricter and refuses to run it at all. Do the same with gcc: treat every warning as a bug until you have understood it. -Werror turns warnings into errors, so the program will not build until they are fixed.
The four steps inside gcc
- Preprocess (
gcc -E main.c): paste in the#includefiles, replace#definenames, drop comments. - Compile (
gcc -S main.cmakesmain.s): translate C into assembly for your CPU. - Assemble (
gcc -c main.cmakesmain.o): turn assembly into machine code, an object file. - Link: join the object files and the C library (where
printflives) into one program.
Errors from steps 1 to 3 point at a line of your code. Errors from step 4 (the linker) say undefined reference: you used a function that is declared but never defined anywhere.
Quick check
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.