# ==== Compiler and Paths ====
CC      := gcc
# -I../include: Look for header files in the include directory
CFLAGS  := -I../include -Wall -O2
LIBDIR  := ../lib
LIBNAME := USB22IO

# ==== Source and Binary Discovery ====
# Find all .c files and use their filenames as target names
EXAMPLES := $(basename $(notdir $(wildcard *.c)))

# ==== Library Path Configuration ====
# Define the physical paths of the library files for dependency tracking
LIB_A  := $(LIBDIR)/lib$(LIBNAME).a
LIB_SO := $(LIBDIR)/lib$(LIBNAME).so

# ==== Linker Logic ====
# Check if the Shared Object (.so) exists to determine the linking method
ifeq ($(wildcard $(LIB_SO)),)
    # Use Static Library if .so is not found
    LIBS    := $(LIB_A)
    LIB_DEP := $(LIB_A)
else
    # Use Dynamic Library if .so exists
    LIBS    := -L$(LIBDIR) -l$(LIBNAME)
    # -Wl,-rpath: Set the search path for shared libraries at runtime
    LDFLAGS := -Wl,-rpath=$(LIBDIR)
    LIB_DEP := $(LIB_SO)
endif

# ==== Build Rules ====
all: $(EXAMPLES)

# Compile each example
# The executable now depends on both the .c file AND the library file ($(LIB_DEP))
$(EXAMPLES): %: %.c $(LIB_DEP)
	$(CC) $(CFLAGS) $< $(LIBS) -o $@ $(LDFLAGS)

# ==== Cleanup ====
clean:
	rm -f $(EXAMPLES)

.PHONY: all clean
