EDIT: Essentially, I am trying to do the same thing as typing \"javac sim.java\" and then \"java sim (commands)\". Is there a way to replace this using a makefile?
S
For a simple project without many files or dependencies, I simply use scripts.
To build:
javac -cp .;* *.java
To run:
java -cp .;* SomeMainClass
Replace .
with whatever path(s) you need for your source. The * will use any jar on the default path or use a different path like lib/*
.
make executes a recipe by executing its dependencies, then the recipe itself. Therefore if you add a command which runs your compiled code to the top recipe, typing 'make' will also run the code after it is compiled. I cannot believe how many people do not know this!
Something like:
sim: sim.class
java sim
Will do what your tutor requires.
Using make with java can be an exercise in driving screws with a hammer as soon as you have more than one class.
Working java code will use packages. So you'll have a complex directory tree that mirrors your package structure, with your .java source files in it. Writing make rules that 'see' all those files is a pain.
You should invoke javac on all your source files at the same time to get correct results. So, the usual make pattern of 'run one command to turn one source file into one compiled file' does not work so well.
However, it seems as if your main problem at the moment is that you expect java to produce an executable; a file with a name like 'sim'. Nope, not going to happen in any simple way. The java compiler produces .class files; a whole tree of them for your source files. You can run directly from them, or you can package them up in a JAR file.
To get all the way to something that appears to be a simple command line executable, you need to use a more complex tool that wraps all this up with a script on the front.
For now, you just need to do:
java -cp . NAME_OF_THE_CLASS_IN_sim.java
to run after your makefile completes.
If you have a simple directory layout like the following,
root/
src/
ExampleClass.java
AnotherClass.java
out/
makefile
you could create your makefile
like this:
##
# source directory
##
SRC_DIR := src
##
# output directory
##
OUT_DIR := out
##
# sources
##
SRCS := $(wildcard $(SRC_DIR)/*.java)
##
# classes
##
CLS := $(SRCS:$(SRC_DIR)/%.java=$(OUT_DIR)/%.class)
##
# compiler and compiler flags
##
JC := javac
JCFLAGS := -d $(OUT_DIR)/ -cp $(SRC_DIR)/
##
# suffixes
##
.SUFFIXES: .java
##
# targets that do not produce output files
##
.PHONY: all clean
##
# default target(s)
##
all: $(CLS)
$(CLS): $(OUT_DIR)/%.class: $(SRC_DIR)/%.java
$(JC) $(JCFLAGS) $<
##
# clean up any output files
##
clean:
rm $(OUT_DIR)/*.class