# ============================================================
# Makefile for x86_64 Assembly Examples (macOS / macho64)
#
# Usage:
#   make              — build all examples
#   make hello        — build a single example
#   make run-hello    — build and run a single example
#   make run-all      — build and run every example
#   make clean        — remove all object files and binaries
#
# Requirements:
#   nasm  (brew install nasm)
#   clang (ships with Xcode Command Line Tools)
# ============================================================

ASM      := nasm
ASMFLAGS := -f macho64
LD       := clang
LDFLAGS  := -arch x86_64

# Automatically discover every .asm file in this directory
SRCS := $(wildcard *.asm)
BINS := $(SRCS:.asm=)

# C + inline asm examples (compiled directly with clang)
C_BINS := 19_inline_asm

ALL_BINS := $(BINS) $(C_BINS)

.PHONY: all clean run-all $(addprefix run-,$(ALL_BINS))

# ---- Default target: build everything ----------------------
all: $(BINS) $(C_BINS)

# ---- Pattern rule: .asm -> binary --------------------------
# Step 1: assemble to object file
# Step 2: link with clang (automatically includes libc)
# Step 3: remove the intermediate .o file
%: %.asm
	@echo ">>> Assembling $<"
	$(ASM) $(ASMFLAGS) $< -o $*.o
	@echo ">>> Linking    $*"
	$(LD) $(LDFLAGS) $*.o -o $@
	@rm -f $*.o
	@echo ""

# ---- run-<name>: build then execute ------------------------
run-%: %
	@echo "========================================"
	@echo "  Running: $*"
	@echo "========================================"
	@./$*
	@echo ""

# ---- Explicit rule: C + inline asm -------------------------
19_inline_asm: 19_inline_asm.c
	@echo ">>> Compiling  $<"
	$(LD) $(LDFLAGS) -O2 $< -o $@
	@echo ""

# ---- run-all: run every example in order ------------------
run-all: all
	@for bin in $(sort $(ALL_BINS)); do \
		echo "========================================"; \
		echo "  Running: $$bin";                        \
		echo "========================================"; \
		./$$bin;                                        \
		echo "";                                        \
	done

# ---- clean -------------------------------------------------
clean:
	@rm -f *.o $(ALL_BINS)
	@echo "Cleaned."
