RunningPig RunningPig - 1 year ago 66
Java Question

Redirect the Java output in a Makefile

I am a new to Makefiles and I am currently writing one. This is what I have so far:

cc = gcc
EXE = foo
JAVAC = javac
JRE = java
PAGER = less
TEST_OUT = test.out
EXP_OUT = expected.out

#clean run-py run-c read run-java save-java and test-java are all phony targets.

foo.o : foo.c foo.h
$(cc) -c foo.c

main.o: main.c foo.h
$(cc) -c main.c

$(EXE): foo.o main.out
$(cc) -o$(EXE) main.o foo.o

run-c: $(EXE)




run-java: foo.class
$(JRE) foo

save-java: foo.class
$(JRE) foo > $(TEST_OUT)

test-java: $(TEST_OUT) $(EXP_OUT)
-@if diff $(TEST_OUT) $(EXP_OUT) &> /dev/null ; then \
echo "Passed!" ;\
else \
echo "Not the same!" ;\

rm foo.o\
rm main.o\
rm $(EXE)\
rm run-c\
rm run-py\
rm foo.class\
rm rn0java\
rm save-java\
rm test\java

In the
, I want to run my Java program, but redirect the output to
. How can I achieve this? Also, in one tutorial, I found that someone used
-\rm xxx
. Is it any different from simply writing
rm xxx

This is the output:
make: *** No rule to make target 'test.out', needed by 'test-java'. Stop.

I guess my redirection is still wrong.

Answer Source

Other than the fact that I'm not sure what the relationship is between your C and java programs, here's what I think you're trying to do

target    := foo
test      := test.out
expected  := expected.out

JAVAC     := javac
JRE       := java

main.o $(target).o: %.o: %.h
$(target): $(target).o main.o

    $(JAVAC) $(JAVAFLAGS) $^

$(TEST_OUT): $(target).class
    $(JRE) $< > $@

.PHONY: java-test clean

java-test: $(TEST_OUT) $(EXP_OUT)
    diff -q $^

clean: ; $(RM) $(target).o main.o $(target) $(target).class
  • Either CC should be a environment variable on the host computer, or cc should be a file link to your default compiler (or the compiler itself), you shouldn't need to define it in the makefile. Make sets CC to cc by default.
  • I don't see any use for a lot of the supposedly .PHONY targets you mentioned, also why would you delete them? They aren't files
  • Make already knows how to compile C source files, and it'll also link foo automatically because one of its prerequisites is foo.o.
  • diff already has a "are these two files the same" flag (-q).
  • You should have a .PHONY target named all at the top that executes the default action, but I can't tell what that would be in this case.