Compiling with gcc
Challenge Gallery
Quick Reference
Essential commands:
| Command | What It Does |
|---|---|
gcc hello.c |
Compile, output a.out |
gcc -o hello hello.c |
Compile, output hello |
gcc -Wall -o hello hello.c |
Compile with all warnings (use this) |
gcc -Wall -g -o hello hello.c |
Compile with warnings + debug symbols |
gcc -c hello.c |
Compile only, produce hello.o |
./hello |
Run the compiled program |
echo $? |
Check exit code (0 = success) |
gcc flags:
| Flag | Meaning |
|---|---|
-o name |
Name the output file |
-Wall |
Enable all common warnings |
-g |
Include debug info (for gdb) |
-c |
Compile only, don’t link (produces .o) |
-lm |
Link the math library |
-std=c99 |
Use the C99 standard |
The compilation pipeline:
hello.c ──▸ Preprocess ──▸ Compile ──▸ Assemble ──▸ Link ──▸ hello
(#include, (C → asm) (asm → .o) (.o → exe)
#define)
gcc -o hello hello.c runs all four stages automatically.
How It Works
Compile and Run
# Compile with warnings
student@ubuntu:~/cscd240$ gcc -Wall -o hello hello.c
# Run it
student@ubuntu:~/cscd240$ ./hello
Hello, World!
# Check the exit code
student@ubuntu:~/cscd240$ echo $?
0
student@ubuntu:~/cscd240$ gcc -Wall -o hello hello.c
# Run it
student@ubuntu:~/cscd240$ ./hello
Hello, World!
# Check the exit code
student@ubuntu:~/cscd240$ echo $?
0
What -Wall Catches
# Without -Wall: compiles silently despite a problem
student@ubuntu:~/cscd240$ gcc -o broken broken.c
# With -Wall: warns you
student@ubuntu:~/cscd240$ gcc -Wall -o broken broken.c
broken.c: In function 'main':
broken.c:5:5: warning: unused variable 'x' [-Wunused-variable]
5 | int x;
| ^
student@ubuntu:~/cscd240$ gcc -o broken broken.c
# With -Wall: warns you
student@ubuntu:~/cscd240$ gcc -Wall -o broken broken.c
broken.c: In function 'main':
broken.c:5:5: warning: unused variable 'x' [-Wunused-variable]
5 | int x;
| ^
Minimal C Program Anatomy
#include <stdio.h> // Standard I/O library (for printf)
int main(void) { // Entry point -- every C program starts here
printf("Hello!\n"); // Print to stdout
return 0; // Exit code: 0 = success
}
Common Pitfalls
- Forgetting
-Wall– Without it, gcc hides bugs that silently corrupt your program at runtime. Non-negotiable in this course. gcc -o hello.c hello– Arguments are swapped. This overwrites your source code with the binary. Always:gcc -o hello hello.c.- Missing
#include– Forgetting<stdio.h>gives “implicit declaration” warnings. Each standard library function has a required header. - No
./prefix –hellosearches PATH and fails../helloruns the program in the current directory. - Confusing warnings and errors – Errors stop compilation. Warnings don’t, but treat them as bugs anyway.
- Missing
-lmfor math functions –sqrt(),sin(),pow()need-lmor you get “undefined reference” linker errors.