# =============================================================================
# Makefile for CMU 15-213 Lecture 18 (system-level I/O)
# =============================================================================
#
#   make run      build and run all five demos
#   make clean    also removes the scratch files the demos write under build/
#
# Every demo links rio.c, the Robust I/O package introduced here and reused by
# Lecture 20. Unix I/O is a kernel service, so there is nothing to cross-compile.
# -----------------------------------------------------------------------------

CC     ?= cc
CFLAGS := -std=c11 -O2 -Wall -Wextra

DEMOS := build/01_unix_io build/02_short_counts build/03_descriptors \
         build/04_redirect build/05_buffering

.PHONY: all run clean
all: $(DEMOS)

build:
	mkdir -p build

# rio.o is shared by every demo
build/rio.o: rio.c rio.h | build
	$(CC) $(CFLAGS) -c -o $@ rio.c

build/%: %.c rio.h build/rio.o | build
	$(CC) $(CFLAGS) -o $@ $< build/rio.o

# The demos are named 01_unix_io.c etc., so the pattern rule above needs the
# full stem; these explicit targets keep the names readable.
build/01_unix_io:      01_unix_io.c      rio.h build/rio.o | build
	$(CC) $(CFLAGS) -o $@ 01_unix_io.c build/rio.o
build/02_short_counts: 02_short_counts.c rio.h build/rio.o | build
	$(CC) $(CFLAGS) -o $@ 02_short_counts.c build/rio.o
build/03_descriptors:  03_descriptors.c  rio.h build/rio.o | build
	$(CC) $(CFLAGS) -o $@ 03_descriptors.c build/rio.o
build/04_redirect:     04_redirect.c     rio.h build/rio.o | build
	$(CC) $(CFLAGS) -o $@ 04_redirect.c build/rio.o
build/05_buffering:    05_buffering.c    rio.h build/rio.o | build
	$(CC) $(CFLAGS) -o $@ 05_buffering.c build/rio.o

run: all
	@./build/01_unix_io
	@echo; ./build/02_short_counts
	@echo; ./build/03_descriptors
	@echo; ./build/04_redirect
	@echo; ./build/05_buffering

clean:
	rm -rf build __pycache__
