# ----------------------------------------------------------------------
# Generic Static Library Makefile
#
# Place this Makefile in any library source directory.
#
# Directory Layout
# ----------------
#   *.c    Source files
#   *.h    Internal/private headers (optional)
#
# Public headers:
#   ../include
#
# Output library:
#   ../lib/lib<directory>.a
#
# Example:
#   vtape/      -> ../lib/libvtape.a
#   viebcopy/   -> ../lib/libviebcopy.a
# ----------------------------------------------------------------------

# Tools
CC ?= gcc
AR ?= ar

# Library name derived automatically from the directory name
LIBNAME := $(notdir $(CURDIR))
LIB     := lib$(LIBNAME).a

# Directories
INCDIR  := ../include
DESTDIR := ../lib

# Sources
SRC := $(wildcard *.c)
OBJ := $(SRC:.c=.o)
DEP := $(OBJ:.o=.d)

# Compiler options
CPPFLAGS ?= -I$(INCDIR)
CFLAGS   ?= -std=c11 -O2 -Wall -Wextra -Wpedantic
CFLAGS   += -MMD -MP
ARFLAGS  ?= rcs

# ----------------------------------------------------------------------

# Default target
all: $(LIB) install

# Ensure there is at least one source file
ifeq ($(strip $(SRC)),)
$(error No C source files found in $(CURDIR))
endif

# Build the library
$(LIB): $(OBJ)
	$(AR) $(ARFLAGS) $@ $^

# Compile source files
%.o: %.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

# Install library
install: $(LIB)
	mkdir -p $(DESTDIR)
	cp -f $(LIB) $(DESTDIR)/

# Cleanup
clean:
	rm -f $(OBJ) $(DEP) $(LIB)

distclean: clean
	rm -f $(DESTDIR)/$(LIB)

# Automatically generated header dependencies
-include $(DEP)

.PHONY: all install clean distclean
