How to use the zig compiler in order to compile nim code?
Asked Answered
T

2

6

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?

Therewith answered 13/8, 2022 at 15:44 Comment(0)
T
4

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:

  1. Install zig
  2. Write a bash- or other shell-script called 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 $@
  1. You can now call nim and tell clang to use zigccfor 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" \
Therewith answered 13/8, 2022 at 15:44 Comment(0)
B
2

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(" "&paramStr(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...

Brunk answered 20/10, 2022 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.