Reputation: 1882
Nim turns its own code into C code and compiles that using C-compilers. Zig has its own compiler that has many nice features that would make you want to use it, such as allowing you to choose which glibc version to dynamically link against, or easier cross-compilation.
Therefore, I would like to compile my nim-code using the zig compiler, but is that even possible?
Upvotes: 7
Views: 1719
Reputation: 21
Write a Nim program (zigcc.nim compiles to zigcc.exe):
import std/osproc
import os
var pStr: string = "zig cc"
for i in 1..paramCount():
pStr.add(" "¶mStr(i))
discard execShellCmd(pStr)
Set your environment path variables with nim.exe & zig.exe paths, copy zigcc.exe to Zig homedir and call Nim like this:
nim c --cc:clang --clang.exe="zigcc" --clang.linkerexe="zigcc" yourFileName.nim
And magic happens...
Upvotes: 2
Reputation: 1882
Nim does provide ways to use the zig compiler, due to Clang being one of its viable backends.
To use it, you need to use the clang compiler AND pass flags to explicitly use zig's compiler for linking and compiling. The process isn't complicated, but does involve multiple steps:
zigcc
whose sole purpose it is to call the zig compiler. This is necessary as the flag that determines which compiler to use doesn't like spaces in its argument but we do need it for this one. Once written, move zigcc
into a directory that is on your PATH environment variable, e.g. /usr/local/bin
on Linux, OR add the path of the directory that contains your zigcc
script to the PATH variable.Alternatively, you can just install this package via nimble (nimble install https://github.com/enthus1ast/zigcc
) which contains exactly such a script that gets installed into the nimble directory which will already be on your path.
Should you want to write your own shell-script, below an example on how it can look with bash:
#!/bin/sh
zig cc $@
zigcc
for the compilation. Find below an example bash script that you can use for these purposes:#!/bin/sh
nim c \
--cc:clang \
--clang.exe="zigcc" \
--clang.linkerexe="zigcc" \
--forceBuild:on \
--opt:speed \
src/<YOUR_MAIN_FILE>.nim
If you want to use zigcc for specifying a glibc version you can do so by just adding these flags to the command above (replace X.XX with the corresponding glibc version that you want):
--passC:"-target x86_64-linux-gnu.X.XX -fno-sanitize=undefined" \
--passL:"-target x86_64-linux-gnu.X.XX -fno-sanitize=undefined" \
Upvotes: 4