I'm curious how to get Nim to build and export C library components. I've got some .exportc. procs but also want to export some C library functions imported using .compile. or .importc..
Suggestions? I've tried a couple of routes the other day but couldn't get the right combination.
If I'm understanding correctly, you are compiling a static or dynamic library, in which you are including C code using {.compile.}, and you want whatever is in those C files to be accessible to C code that is linked against your lib (or Nim via importc I guess)?
If so, you shouldn't need to do anything. C doesn't have namespaces, as long as the symbols are not static, they should be accessible (you'll need to write a header file with prototypes though).
If so, you shouldn't need to do anything. C doesn't have namespaces, as long as the symbols are not static, they should be accessible (you'll need to write a header file with prototypes though).
That’s what I thought too. But Nim didn’t seem to be including the compiled C files. They’re in the Nim object cache but don’t seem to be compiled / linked in with lib mode.
It’s for building an existing C library in and there’s headers already. Maybe be I’ll try a simpler setup to test.
in the Nim object cache but don’t seem to be[..]linkedin
Maybe add --passL:foo.o ?
maybe this is too naive a toy example, but it works:
clib.c
int sum(int a,int b){return a+b;}
nimlib.nim
{.compile:"clib.c".}
#proc sum(a,b:int32):int32{.importc.}
## as @auxym says; if it's not static, it's exported
## even if you dont use it in the nim file
when compileOption("app","lib"):
{.push,dynlib.}
proc mul(a,b:int32):int32{.exportc.} = a * b
nimlib.h
int sum(int a, int b);
int mul(int a, int b);
main.c
#include "nimlib.h"
#define i(x) *a[i] - '0'
int main(int _, char** a){
return mul(sum(i(1),i(2)),sum(i(3),i(4)));
}
building and running:
$ nim c -d:release --app:staticLib --noMain nimlib.nim
$ gcc main.c -L. -l:libnimlib.a
--OR--
$ nim c -d:release --app:lib --noMain nimlib.nim
$gcc main.c -L. -Wl,-rpath,. -lnimlib
$ ./a.out 1 2 3 4; echo $?
21
The compile pragma can be used to compile and link a C/C++ source file with the project
I've persoally used {.compile.} in the past and haven't had a problem, Nim was building and linking the requested C files as requested.