Should we link the compiled `.klib` file manually ...
# kotlin-native
l
Should we link the compiled
.klib
file manually when using the Gradle plugin? I'm trying to call a function named
reverse
written in C from a Kotlin code, but running
./gradlew runProgram
show the error below.
Copy code
> Configure project :
Kotlin Multiplatform Projects are an experimental feature.

> Task :cinteropReverseLinux UP-TO-DATE

> Task :linkReleaseExecutableLinux
/home/lucas/.konan/dependencies/clang-llvm-6.0.1-linux-x86-64/bin/ld.lld: error: undefined symbol: reverse
>>> referenced by ld-temp.o
>>>               /tmp/konan_temp3346060776025102598/combined.o:(reverse_kniBridge0)
error: /home/lucas/.konan/dependencies/clang-llvm-6.0.1-linux-x86-64/bin/ld.lld invocation reported errors

> Task :linkReleaseExecutableLinux FAILED
Sample: https://github.com/lucasvalenteds/kotlin-native-cinterop
m
You need to compile your C code to static library, and add to .def file something like this:
Copy code
staticLibraries = reverse.a
libraryPaths = build
(or where you put it, relative or absolute path) Then it will be embedded in .klib and added in linker options automatically.
👍 1
Or in simple cases it can be done directly in .def file:
Copy code
package reverse

---

#include <stdlib.h> // malloc, free
#include <string.h> // strlen

static inline char* reverse(char* text) {
    // Allocate memory to save the reversed text
    size_t textLength = strlen(text);
    char* textReversed = (char*) malloc((textLength + 1) * sizeof(char));
    textReversed[textLength] = '\0';

    // Reverse the text
    int i = 0;
    for(i = 0; i < textLength; i++) {
        textReversed[i] = text[textLength - 1 - i];
    }

    return textReversed;
}
l
Thank you @msink. It's working now.