# Makefile for compiling popcount.c

CC=gcc
CFLAGS=-g -Wall -Wextra -pedantic -std=gnu11

# Detect architecture
UNAME_M := $(shell uname -m)

ifeq ($(UNAME_M),x86_64)
	# Requires a CPU with SSE 4.2 support (Intel Nehalem or newer)
	HW_FLAG = -mpopcnt
else ifeq ($(UNAME_M),arm64)
	# On Apple Silicon (arm64), popcount is typically enabled by default
	# but we can use -march=native for optimization.
	HW_FLAG = -march=native
else
	HW_FLAG = 
endif

# Default target: build both versions
all: popcount_no_hw popcount_hw popcount_hw_optimized popcount_no_hw_optimized

# Target for the version without hardware popcount support
popcount_no_hw: popcount.c
	$(CC) $(CFLAGS) -o $@ $<

popcount_no_hw_optimized: popcount.c
	$(CC) $(CFLAGS) -O3 -o $@ $<

# Target for the version with hardware popcount support enabled
popcount_hw: popcount.c
	$(CC) $(CFLAGS) $(HW_FLAG) -o $@ $<

popcount_hw_optimized: popcount.c
	$(CC) $(CFLAGS) -O3 $(HW_FLAG) -o $@ $<

# Clean up the built binaries
clean:
	rm -f popcount_no_hw popcount_hw popcount_no_hw_optimized popcount_hw_optimized

.PHONY: all clean
