exaloop / codon

A high-performance, zero-overhead, extensible Python compiler using LLVM
https://docs.exaloop.io/codon
Other
13.95k stars 498 forks source link

Linking library in codon build for shared library #563

Closed gyuro closed 3 weeks ago

gyuro commented 3 weeks ago

I'm working on a project where the main function calls a run function, which is linked to an exported codon library (librun.so). This codon library, in turn, is linked to a shared library named libtest.so.

However, I'm facing a challenge because the codon build doesn't have a feature that allows the user to include a dependent library when creating a shared library. This is causing inconvenience as I have to update the library path each time, especially since the library name changes with every run due to some reason.

Could you give me a solution to import the dependent library for the codon build?

Here's my code:

In main.cpp:

extern "C" void run();
int main() {
   run();
   return 0;
}

In run.codon:

LIBRARY = "libtest.so"
from C import LIBRARY.test(float, float) -> float

@export
def run():
    res = test(2.0, 3.0)

In libtest.so:

float test(float x, float y) {
   return x * y;
}

These are the commands that I used to build.

codon build --release --relocation-model=pic --lib -o librun.so run.codon g++ -o main main.cpp -L . -lrun

arshajii commented 3 weeks ago

Hi @gyuro -- you can pass custom flags to the C compiler/linker that Codon uses to generate the shared library via the -linker-flags argument of codon, e.g.

codon build ... -linker-flags '-ltest' ... run.codon

Does that work in your case?

gyuro commented 3 weeks ago

Yes, it appears to be functioning. However, should LIBRARY still be configured in the codon? Is it possible to import functions from the shared library without specifying LIBRARY?

arshajii commented 3 weeks ago

If you're linking the libtest.so library then you should be able to just use from C import without specifying the library explicitly:

from C import test(float, float) -> float

Does that work?

gyuro commented 3 weeks ago

Amazing, it functions perfectly. Appreciate your help