Skip to content

Instantly share code, notes, and snippets.

@the-mikedavis
Created August 24, 2018 15:55
Show Gist options
  • Save the-mikedavis/23a4c0fc4e2338c5535c3b2245257c83 to your computer and use it in GitHub Desktop.
Save the-mikedavis/23a4c0fc4e2338c5535c3b2245257c83 to your computer and use it in GitHub Desktop.
Minimalistic Java Makefile
JFLAGS = -g
JC = javac
.SUFFIXES: .java .class
.java.class:
$(JC) $(JFLAGS) $*.java
CLASSES = \
main.java \
Person.java \
Place.java \
Thing.java
default: classes
classes: $(CLASSES:.java=.class)
clean:
$(RM) *.class
run:
java main
@the-mikedavis
Copy link
Author

Save this file into your src/ directory and change the list in CLASSES to be your files. Change the command in run: to be your main java class (hint: whatever you would do to run the program, i.e. java <main-class>). Then run $ make to compile your code. Run $ make run to run the code and $ make clean to clean up the *.class files.

@GavinRay97
Copy link

The below works a lot better IMO, and it respects the usual Maven/Gradle src/main/java and target/classes directory structure:

JAVA_VERSION = 20
JAVAC = /home/user/downloads/jdk-20-vahalla-20-75/bin/javac
JAVA = /home/user/downloads/jdk-20-vahalla-20-75/bin/java

JAVA_COMPILE_OPTIONS = --enable-preview --release $(JAVA_VERSION)
JAVA_OPTIONS = --enable-preview

JAVA_MAIN_CLASS = org.example.Application
JAVA_SOURCES = $(wildcard src/main/java/**/**/*.java)
JAVA_CLASSES = $(patsubst src/main/java/%.java, target/classes/%.class, $(JAVA_SOURCES))

# Compile the Java source files
compile: $(JAVA_CLASSES)
	$(info Java source files: $(JAVA_SOURCES))
	$(info Java class files: $(JAVA_CLASSES))

# Run the Java main class
run: compile
	$(JAVA) $(JAVA_OPTIONS) -cp target/classes $(JAVA_MAIN_CLASS)

# Clean the target directory
clean:
	rm -rf target

# Compile the Java source files
target/classes/%.class: src/main/java/%.java
	$(JAVAC) $(JAVA_COMPILE_OPTIONS) -d target/classes $<

# Create the target directory
target/classes:
	mkdir -p target/classes

# Make the target directory a dependency of the Java class files
$(JAVA_CLASSES): target/classes
compile: target/classes
clean: target/classes
run: target/classes
default: target/classes

default: run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment