Kotlin/Native libraries

the above command will produce a bar.klib with the compiled contents of foo.kt.

To link to a library use the -library <name> or -l <name> flag. For example:

  1. $ kotlinc qux.kt -l bar

the above command will produce a program.kexe out of qux.kt and bar.klib

cinterop tool specifics

The cinterop tool produces .klib wrappers for native libraries as its main output. For example, using the simple libgit2.def native library definition file provided in your Kotlin/Native distribution

  1. $ cinterop -def samples/gitchurn/src/nativeInterop/cinterop/libgit2.def -compiler-option -I/usr/local/include -o libgit2

we will obtain libgit2.klib.

See more details in INTEROP.md

The klib library management utility allows you to inspect and install the libraries.

The following commands are available.

  1. $ klib contents <name>

To inspect the bookkeeping details of the library

  1. $ klib info <name>

To install the library to the default location use

    To remove the library from the default repository use

    All of the above commands accept an additional -repository <directory> argument for specifying a repository different to the default one.

    1. $ klib <command> <name> -repository <directory>

    Several examples

    First let’s create a library. Place the tiny library source code into kotlinizer.kt:

    1. package kotlinizer
    2. val String.kotlinized
    3. get() = "Kotlin $this"
    1. $ kotlinc kotlinizer.kt -p library -o kotlinizer

    The library has been created in the current directory:

    1. $ ls kotlinizer.klib
    2. kotlinizer.klib

    Now let’s check out the contents of the library:

    1. $ klib contents kotlinizer

    We can install kotlinizer to the default repository:

    1. $ rm kotlinizer.klib

    Create a very short program and place it into a use.kt :

    1. import kotlinizer.*
    2. println("Hello, ${"world".kotlinized}!")
    3. }

    Now compile the program linking with the library we have just created:

    1. $ kotlinc use.kt -l kotlinizer -o kohello

    And run the program:

    1. $ ./kohello.kexe
    2. Hello, Kotlin world!

    Have fun!

    Advanced topics

    When given a -library foo flag, the compiler searches the foo library in the following order:

    1. * Current compilation directory or an absolute path.
    2. * All repositories specified with `-repo` flag.
    3. * Libraries installed in the default repository (For now the default is `~/.konan`, however it could be changed by setting **KONAN_DATA_DIR** environment variable).

    The library format

    Kotlin/Native libraries are zip files containing a predefined directory structure, with the following layout:

    foo.klib when unpacked as foo/ gives us:

    An example layout can be found in klib/stdlib directory of your installation.