How do I set the name of my native library or executable to be the name of the project?


(Scott Palmer) #1

I want to write a generic script for building some native libraries that are plugins for my mixed Java/Native product. These libraries use JNI and may have dependencies on other plugins (which will be PreBuilt dependencies)

I have my project building, finding dependencies and adding the appropriate header paths and linking to the libraries. It adds the JDK headers and libraries for JNI etc.

The problem is that every project produces a file called libmain.dylib or libmain.so. It makes sense to me that the source set is always called ‘main’ so it matches the sort of structure used for Java projects and every gradle file doesn’t need to be different in terms of declaring the source set and the dependencies for the source set, e.g. I will always have:

model {
  buildTypes {
    debug
    release
  }
  repositories {
    libs(PrebuiltLibraries) {
      // This is too complicated - built-in support for JNI would be nice
      jvm {
        headers.srcDir "${System.getenv('JAVA_HOME')}/include"
//JAVA_HOME must be set to point to a JDK
        headers.srcDir "${System.getenv('JAVA_HOME')}/include/darwin"
        binaries.withType(SharedLibraryBinary) {
          File libFile = new File("${System.getenv('JAVA_HOME')}/jre/lib/server/libjvm.dylib") // OS X
          if (!libFile.exists()) {
            libFile = new File("${System.getenv('JAVA_HOME')}/jre/lib/i386/client/libjvm.so") // 32-bit Linux
          }
          if (!libFile.exists()) {
            libFile = new File("${System.getenv('JAVA_HOME')}/lib/jvm.lib") // Windows (JAVA_HOME picks 32 vs 64-bit)
          }
          // more cases to cover later...
        }
      }
    }
  }
}
  sources {
  main {
    cpp {
...
    }
  }
}
  sources.main.cpp.lib library: 'jvm', linkage: 'shared'

That makes it easy to just always apply this file to my JNI projects.

I don’t want to change the name of the source set to change the name of the final library file because then I have to change it in a bunch of places like the lines that declare the dependencies.


(Gary Hale) #2

You should be able to do something like this:

libraries {
    main {
        baseName = project.name
    }
}

This will produce a binary with a name like “lib${project.name}.so” or “lib${project.name}.dylib”


(Scott Palmer) #3

That worked great. Thanks!