preface

Although it is well known that Java source code is compiled into bytecode files by Javac and then Run Anywhere by JVM, some players want to compile it into an EXE. Of course, this is possible. I haven’t tried this yet, but it’s easy to do. The principle is to package the JRE and jar together and store it in an EXE file. Then when you run the EXE, release the JRE and jar file and then call java-jar to execute the jar package. The resulting EXE is very large and does not leave the JVM.

Is there any other way, of course, to use GCJ, which stands for GNU Compiler for the Java Programming Language, to directly compile Java files into native machine instructions? This allows Java programs to run independently of the JVM environment, and Java files to be compiled into bytecode files. GCJ’s implementation is incomplete, but it supports most Java features, including collections, networking, reflection, serialization, JNI, and RMI.

GCJ

The installation

The following uses Linux as an example. The installation command is as follows:

sudo apt-get install  gcj-jdk
Copy the code

Generate an executable file

In writing a Java Hello World file:

public class Test {
    public static void main(String... A ‮) {
        System.out.println("HelloWorld"); }}Copy the code

The following is a two-step compilation and linking command:

GCJ --main=Test -o Test test. o #Copy the code

The GCJ compiler first compiles a.o object file with Java source code. The contents of this file are local machine instructions that can be executed directly by the CPU. GCJ then links this object file to generate an executable file.

You can also compile and link with a command like this:

gcj --main=Test -o Test Test.java
Copy the code

–main=Test tells the link which class’s main() method to use as the entry to the executable.

Then run:

./Test 
HelloWorld
Copy the code

Are you stunned? But the final size is still a bit large, 16.1KB.

Generate Java bytecode files

The -c argument tells GCJ to compile to a Java bytecode file, that is, to generate a class file that can be run with a Java command.


gcj -C Test.java 

java Test 

HelloWorld

Copy the code

Compile the Jar

To compile a JAR into an executable, you first package the project into a JAR package through the IDE, or through the jar command, and then compile and link it.

jar cvf Test.jar *.class

gcj -c Test.jar

gcj --main=Test -o Test Test.o

./Test 
Copy the code

Although GCJ can compile Java source code into local machine instructions, few people seem to do so. First of all, the GCJ compiler can only support Java’s base libraries by default, and other third-party GCJ compilers can’t.