Verhogen
Verhogen

Reputation: 28641

Java Makefile Output Single Executable

How can I create a Makefile to compile my Java program with a single source file located in src/Hello.java to ouput a file that I can run with ./prog

Upvotes: 1

Views: 2236

Answers (2)

Anon
Anon

Reputation: 2674

Make is not a great tool for building Java programs, primarily because its core design is to identify out-of-date sources (either source or object files) and apply transforms to them. The Java compiler handles this dependency checking already, and defining a Make rule for Java compilation is more trouble than it's worth.

Adrian Smith has already suggested Ant. I'm going to suggest Maven as an alternative.

My main reason for this suggestion is that it's very easy to get a simple project going in Maven: you can tell Maven to create the entire directory structure, and then it just works. And although you may not like the directory structure that Maven creates, there's a benefit to the consistency if you're working in a large project. Maven does have its limitations, and some of them are extremely painful, but you generally won't run into them until you have the knowledge to work around them.

As for running a Java program, you need to invoke the JVM somewhere along the line. A shell script is one approach, but generally it's easier just to invoke the JVM directly. If you create an "executable JAR" (which Maven will do for you, including options to include all dependencies), you can invoke it like this:

java -jar executable.jar

Upvotes: 2

Adrian Smith
Adrian Smith

Reputation: 17593

(1) Take a look at http://ant.apache.org/ - that's a build tool suited to Java better than make. For example check out the javac command in ant.

(2) You have to run java programs by running the java virtual machine (java) and by telling it what to execute. There is no ./xxx way to run a program in java; that method executes scripts or executable programs, and a compiled java program is bytecode which is neither. What you need is to create a little shell script, call it "Hello", give it execute permissions with chmod, its contents should be something like:

#!/bin/bash

java -cp . Hello

Upvotes: 2

Related Questions