It is simpler than my code, but there is a problem in your code when you want
to link multiple C files. If 2 C files have same name static variables outside
of function, it would generate redefinition error. In C++, redefinition error
will be also generated when 2 C++ files have same name variables or functions
in anonymous namespace. You can avoid such error by creating 1 nim file per 1
C/C++ files, but I don't think that is not good idea when you want to use many
C/C++ files.
And when you got compile error from C/C++, line number in the error doesn't
match line number in C/C++ files. I think you can fix it by emitting #line N
before C code.
My code might looks like complicated but linkModule template can be placed in
other module and be used in elsewhere without copy&pasting it.
For example: test1.c
static int x = 1;
int getX1() {
return x;
}
Run
test2.c
static int x = 2;
int getX2() {
return x;
}
Run
testc.nim
const
Ccode1 = staticRead"test1.c"
Ccode2 = staticRead"test2.c"
{.emit: Ccode1.}
{.emit: Ccode2.}
Run
sample.nim
import testc
proc getX1(): cint {.importc.}
proc getX2(): cint {.importc.}
echo getX1(), getX2()
Run