'Gradle add native library dir to java.library.path (not for test but for run)

Maybe someone here can help me. I have a Java Project in which I use Gradle and process the whole thing in IntelliJ. (Specs down below)

In my project I use JNI and write my own C++ library (.so file) which I put in a directory in my project e.g. ./native/build/lib/main/debug/libnative.so.

Now, when running my program normally in IntelliJ, I want the VM to add the path of my .so-library to the java.library.path and use it accordingly. At the moment I have to do this for each main class individually by going to Edit Configurations and under Modify Options > Add VM Options add -Djava.library.path=...../native/build/lib/main/debug. But somehow it must be possible to set this globally for all classes in gradle, or not ?

I know you can add in gradle.build the java.library.path for tests like follows

test {
    systemProperty 'java.library.path','path/to/directory'
}

but I don't need this for the tests but for the normal run/start of a main function in a class when clicking the green Arrow in IntelliJ. I already tried to add it in all task like follows

compileJava {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
processResources {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
classes {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
jar {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
startScripts {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
installDist {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}
build {
    "-Djava.library.path=${System.getProperty('java.library.path')}:${project(':native').buildDir}/lib/main/debug"
}

but without success. Note that only in test 'systemProperty' can be used. Since in other tasks a 'No Signature Method exception' is thrown .When I try to start the program I get Exception in thread "main" java.lang.UnsatisfiedLinkError: no native in java.library.path: [/usr/java/packages/lib, /usr/lib64, /lib64, /lib, /usr/lib].

I use here simply the following class:

public class A {
    public static native void print0();

    static {
        System.loadLibrary("native");
    }

    public static void main(String[] args) {
        print0();
    }
}

and yes, it works when i individually set -Djava.library.path... in Run Configuration

Environment:

  • IntelliJ IDEA Ultimate 2021.3.2
  • AdoptOpenJDK 11.0.11+9 hs
  • Gradle 7.1


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source