Kotlin Native C Interop on Fedora 39

It’s been a while since I’ve used Kotlin Native, so I thought I’d try it out again. I’ve been interested in using OpenCL and I thought I’d try to spin up a small demo. However, it didn’t go exactly as planned. When I had tried Kotlin Native a few years ago, the interop story between Kotlin and native code was actually pretty nice, once you figured out how to actually write the code. This time around was much different.

In Kotlin Native, when you want to call native code written in C, you need to create a definition for the cinterop tool, which essentially generates the bindings for you. The files look something like this:

headers = CL/cl.h

compilerOpts.linux = -I/usr/include
linkerOpts.linux = -lOpenCL

And honestly, this actually isn’t bad and it’s pretty understandable. A basic workflow for creating a project follows this route:

  1. Create a gradle project
  2. Configure gradle to use the multiplatform support for Kotlin
  3. Specify the native libraries you need and tie it altogether
  4. Create a directory in your project root for the cinterop definitions(usually somthing like src/nativeInterop/cinterop
  5. Write your definition file
  6. Start importing the C functions and calling them in your code


However, Kotlin Native ships with it’s own buildroot to ensure consistency across multiplatforms. This buildroot is old, especially compared to something that Fedora would typically ship. Turns out, we can work around this, but it takes a bit of stuff that doesn’t seem to be clearly documented anywhere except on the YouTrack site. I was able to fix it but updating my Gradle build script to include some addtional compiler options.

kotlin {
  binaries {
    executable {
      freeCompilerArgs += listOf(
        "-Xoverride-konan-properties=targetSysRoot.linux_x64=/" //Change buildroot location
      + ";libGcc.linux_x64=/lib/gcc/x86_64-redhat-linux/13" //Look for libGcc in the correct place
      + ";linker.linux_x64=/usr/bin/ld.bfd" //Use a proper linker, gold seems to choke on some newer stuff
      + ";crtFilesLocation.linux_x64=usr/lib64" //Tell Kotlin where to find some C runtime libraries
      )
    }
  }
}

After adding this, I have had 0 issues with compiling Kotlin Native code and it doesn’t appear to mess up any of the internals, however, I’ve only written about 4 different small sample programs. You would think changing the build root might cause more issues, but it doesn’t. I, also, found it strange that I had to tell the compiler to use a different linker. At some point in time, it seems that the BFD linker started adding sections to the libraries it generates that the Gold linker can’t support. Instead of just ignoring the sections, the Gold linker just gives up.

Anyway, if you are like one of the 10 people who use Kotlin Native on a Linux desktop or server, I hope you come across this and it helps, instead of finding yourself looking through YouTrack.