CMake to compile java code

后端 未结 1 964
小鲜肉
小鲜肉 2021-02-04 02:41

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.jav

1条回答
  •  迷失自我
    2021-02-04 03:39

    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.

    0 讨论(0)
提交回复
热议问题