Nim backend integration guide describes how to call a Nim function from C.
Example function:
proc fib(a: cint): cint {.exportc.} =
if a <= 2:
result = 1
else:
result = fib(a - 1) + fib(a - 2)
The procedure requires that the Nim compiler is instructed not to create a main
function, avoid linking and creating a header file to FFI from:
$ nim c --noMain --noLinking --header:fib.h fib.nim
To be able to use that function, the C main has to invoke a function called NimMain()
as below:
#include "fib.h"
#include <stdio.h>
int main(void)
{
NimMain();
for (int f = 0; f < 10; f++)
printf("Fib of %d is %d\n", f, fib(f));
return 0;
}
The previously mentioned generated header file is placed in the nimcache
directory. The C compiler has to be instructed to compile all the files under the generated nimcache
sub-directory, nimbase.h
and main.c
:
$ gcc -o m -I$HOME/.cache/nim/fib_d -Ipath/to/nim/lib $HOME/.cache/nim/fib_d/*.c maths.c
How can I instruct the rust compiler to look for those translation units under nimcache
?
NimMain()
function at the top of the main to load its garbage collection. It'd be nice if your example included that call too. – Statistical