CMake to compile java code

2019-03-15 04:31发布

问题:

Is it possible to use CMake to compile and run java code?

From command line the commands that I write on terminal is:

javac -classpath theClasspath mainClass.java

java -classpath theClasspath mainClass

If so, could you please give me an idea of how this can be achieved?

PS: I do not want to generate a jar file; just to compile the java class and if possible to run it.

Thanks.

Update: I have changed the command. I do not know why the additional text was not displayed. It might be because I used "<" and ">".

回答1:

CMake has somewhat limited support for compiling Java code and executing Java class files.

The standard module FindJava can be used to find a JDK installed on the local machine. The standard module UseJava provides a few functions for Java. Among those is a function add_jar to compile Java source files to a jar file.

Here is a small example that demonstrates how to use add_jar. Given the Java sample source file HelloWorld.java:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

The following CMake list file will compile HelloWorld.java to a jar file HelloWorld.jar and also add a CMake test that runs the jar with the JVM:

cmake_minimum_required (VERSION 2.8)

find_package(Java REQUIRED)
include(UseJava)

enable_testing()

project (HelloWorld NONE)

set(CMAKE_JAVA_COMPILE_FLAGS "-source" "1.6" "-target" "1.6")

add_jar(HelloWorld HelloWorld.java)

get_target_property(_jarFile HelloWorld JAR_FILE)
get_target_property(_classDir HelloWorld CLASSDIR)

message(STATUS "Jar file ${_jarFile}")
message(STATUS "Class compiled to ${_classDir}")

add_test(NAME TestHelloWorld COMMAND ${Java_JAVA_EXECUTABLE} -cp ${_jarFile} HelloWorld)

The CMake variable CMAKE_JAVA_COMPILE_FLAGS can be used to specify compile flags. As a side effect the add_jar command will set target properties JAR_FILE and CLASSDIR that can be used to obtain the path to the generated jar file and the compiled class files directory, respectively.



标签: java cmake