Makefiles and debugging
Automate a build with a minimal Makefile and catch bugs with warnings, gdb and sanitizers.
- Read a minimal Makefile with a build rule and a clean rule.
- Enable -Wall -Wextra -Werror and fix every warning.
- Set a breakpoint in gdb and inspect a variable.
- Run a program under AddressSanitizer to catch memory errors.
In plain English
A Makefile is a script that tells the make tool how to build your program, and a rule says which target to build and which files it depends on. Compiler warnings are messages the compiler prints when your code is legal but probably a mistake, and -Wall and -Wextra turn on many of them. gdb is a debugger that lets you pause a running program at a breakpoint and inspect its variables one step at a time. A sanitizer is a tool the compiler builds into your program that catches memory and undefined-behaviour mistakes while it runs, using a flag such as -fsanitize=address.
Step by step
- 1Write a Makefile with a CC variable and a build rule.
- 2Run make and watch it compile app from main.c.
- 3Add -Wall -Wextra -Werror to CFLAGS and fix any warning.
- 4Start gdb, set a breakpoint at main and run.
- 5Add -fsanitize=address and rerun the program on a bad index.
CC = cc
CFLAGS = -Wall -Wextra -Werror -g
app: main.c
$(CC) $(CFLAGS) -o app main.c
clean:
rm -f appCommon mistakes
- Indenting a recipe with spaces instead of a tab makes make fail with a missing-separator error.
- Ignoring a compiler warning is risky, because the code is legal but still does something you did not intend.
- Reading an array past its end is undefined behaviour that sanitizers report but a normal run may hide.
- Setting a breakpoint after the buggy line means the program has already failed before you can inspect it.
Fix the out-of-bounds loop
This loop reads one element past the end of the scores array. Fix the bound so it prints exactly the three scores without touching memory it does not own.
#include <stdio.h>
int main(void) {
int scores[3] = {8, 9, 7};
for (int i = 0; i <= 3; i++) {
printf("%d\n", scores[i]);
}
return 0;
}Which flag builds AddressSanitizer into your program?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.