# For simple projects you could just do:
# SRCFILES += $(wildcard ccan/*/*.c)
-CFLAGS=-g -O3 -Wall -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Werror -I. $(DEPGEN)
+#CCAN_CFLAGS=-g -O3 -Wall -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations
+CCAN_CFLAGS=-g -Wall -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations
+CFLAGS = $(CCAN_CFLAGS) -I. $(DEPGEN) -Werror
-# Automatic dependency generation: makes ccan/*.d files.
+
+default: libccan.a
+
+# Automatic dependency generation: makes ccan/*/*.d files.
DEPGEN=-MD
-include ccan/*/*.d
-# Every directory with .c files is included.
-DIRS=$(filter-out $(EXCLUDE), $(patsubst %/, %, $(sort $(dir $(wildcard ccan/*/*.c)))))
+# Anything with an _info file is a module.
+REALLY_ALL=$(patsubst ccan/%/_info, %, $(wildcard ccan/*/_info))
+
+# Exclude any modules we can't build.
+ALL=$(filter-out $(EXCLUDE), $(REALLY_ALL))
+
+# Anything with C files needs building; dir leaves / on, sort uniquifies
+DIRS=$(patsubst %/, %, $(sort $(foreach m, $(ALL), $(dir $(wildcard ccan/$m/*.c)))))
+
+# Generate everyone's separate Makefiles.
+-include $(foreach dir, $(DIRS), $(dir)-Makefile)
+
+ccan/%-Makefile:
+ @echo $@: $(wildcard ccan/$*/*.[ch]) ccan/$*/_info > $@
+ @echo ccan/$*.o: $(patsubst %.c, %.o, $(wildcard ccan/$*/*.c)) >> $@
# We compile all the ccan/foo/*.o files together into ccan/foo.o
OBJFILES=$(DIRS:=.o)
-libccan.a: $(OBJFILES)
- $(AR) r $@ $^
-
-# Dependencies are autogenerated in the .d files.
# We create all the .o files and link them together.
$(OBJFILES): %.o:
- cd $* && $(CC) -I../.. $(CFLAGS) -c *.c && cd ../.. && $(LD) -r -o $@ `echo $*/*.c ' ' | sed 's/\.c /.o /g'`
+ $(LD) -r -o $@ $^
+libccan.a: $(OBJFILES)
+ $(AR) r $@ $(OBJFILES)