Java and GNU make

I'm an expert in neither Java nor make, but I wanted recently to assemble a wildcard-style Makefile to build a bunch of java files. With compiled-and-linked languages that's easy, since the executable has object/library dependencies. All that's required is a suitable $(OBJECTS) or some such list, a target, and a wildcard rule to build them. With Java there's no target executable, and classes are just sort of built at random and linked at runtime instead.

Anyway, here 'tis. May the next person to poke around search engines for this sort of thing find it useful.



JAVAC=javac
sources = $(wildcard *.java)
classes = $(sources:.java=.class)

all: $(classes)

clean :
	rm -f *.class

%.class : %.java
	$(JAVAC) $<

Explanation: 'sources' gets the list of files matching *.java (yes, just putting *.java would have worked as well). 'classes' gets the result of substituting .java for .class in each one. The 'all' rule ensures that they all get built. The wildcard rule tells make how to build the class files, and ensures that only the changed files get recompiled, which given how slow Java compilers tend to be, is sort of the point. 'javac *.java' is crude and slow.

This works with GNU make (written against 3.79.1).

/