Griffort
Griffort

Reputation: 1305

"Unresolved Reference" when Interop-ing C Library

I am trying to make a militaristic example of reading and executing C code within Kotlin-Native. I am following this article here. However, I'm receiving an "Unresolved Reference" error on the final step. Here are all the files/commands I'm using. My operating system is Windows.

testlib.h

#ifndef MY_TEST_LIB
#define MY_TEST_LIB

int getRandomNumber();

#endif

testlib.c

#include "testlib.h"

#include <stdio.h>
#include <stdlib.h>

int getRandomNumber() {
    return rand();
}

I've compiled these files into a static library named libtestlib.lib. My goal is to call getRandomNumber from within Kotlin Native.


Next I have these kotlin related files:

testlib.def

headers = testlib.h
headerFilter = ./*
compilerOpts = -L. -ltestlib -I.

CLibTest.kt

import testlib.*

fun main(args: Array<String>) {
    println(getRandomNumber())
}

Finally, I'm running these two commands. The first to make the klib:

cinterop -def testlib.def -o testlib


And then this last one to create the executable:

konanc CLibTest.kt -library testlib

Everything works great until this last command, where I receive the following error:

CLibTest.kt:4:10: error: unresolved reference: getRandomNumber println(getRandomNumber())


Could someone point out where I went wrong?

Upvotes: 1

Views: 1070

Answers (3)

Griffort
Griffort

Reputation: 1305

The answer is the combination of suggestions from Svyatoslav Scherbina and Mike Sinkovsky.

The "headerFilter" was incorrect and needed to be removed, and the static library needed to be embedded to the .klib. By setting testlib.def to be:

headers = testlib.h
compilerOpts = -I.
staticLibraries = libtestlib.lib
libraryPaths = .

The issue is resolved and the kotlin file complies/runs without issue!

Upvotes: 1

Svyatoslav Scherbina
Svyatoslav Scherbina

Reputation: 285

headerFilter value in your testlib.def is incorrect. You can try to remove it.

The filter is applied to the value written under #include directive from headers and headers value elements from .def file. None of these strings have ./ prefix.

Upvotes: 1

Mike Sinkovsky
Mike Sinkovsky

Reputation: 126

Windows libraries must be created by msys2-mingw, not msvc.

Something like this (in mingw64 shell):

gcc -c testlib.c -o testlib.o && ar rc testlib.a testlib.o

Upvotes: 2

Related Questions