简体   繁体   English

如何使用 zig 编译器来编译 nim 代码?

[英]How to use the zig compiler in order to compile nim code?

Nim turns its own code into C code and compiles that using C-compilers. Nim 将自己的代码转换为 C 代码并使用 C 编译器进行编译。 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. Zig 有它自己的编译器,它有许多让你想使用它的好特性,比如允许你选择动态链接的 glibc 版本,或者更容易的交叉编译。

Therefore, I would like to compile my nim-code using the zig compiler, but is that even possible?因此,我想使用 zig 编译器编译我的 nim 代码,但这可能吗?

Nim does provide ways to use the zig compiler, due to Clang being one of its viable backends. Nim 确实提供了使用 zig 编译器的方法,因为 Clang 是其可行的后端之一。

To use it, you need to use the clang compiler AND pass flags to explicitly use zig's compiler for linking and compiling.要使用它,您需要使用 clang 编译器并传递标志以显式使用 zig 的编译器进行链接和编译。 The process isn't complicated, but does involve multiple steps:这个过程并不复杂,但确实涉及多个步骤:

  1. Install zig安装 zig
  2. Write a bash- or other shell-script called zigcc whose sole purpose it is to call the zig compiler.编写一个名为zigcc的 bash 或其他 shell 脚本,其唯一目的是调用 zig 编译器。 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, eg /usr/local/bin on Linux, OR add the path of the directory that contains your zigcc script to the PATH variable.编写完成后,将zigcc移动到 PATH 环境变量中的目录中,例如 Linux 上的/usr/local/bin ,或者将包含zigcc脚本的目录的路径添加到 PATH 变量中。

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.或者,您可以通过 nimble ( nimble install https://github.com/enthus1ast/zigcc ) 安装此 package ,其中包含恰好安装到您路径上的 nimble 目录中的脚本。

Should you want to write your own shell-script, below an example on how it can look with bash:如果您想编写自己的 shell 脚本,请参阅下面的示例,了解 bash 的外观:

#!/bin/sh
zig cc $@
  1. You can now call nim and tell clang to use zigcc for the compilation.您现在可以调用 nim 并告诉 clang 使用zigcc进行编译。 Find below an example bash script that you can use for these purposes:在下面查找可用于这些目的的示例 bash 脚本:
#!/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):如果您想使用 zigcc 来指定 glibc 版本,您只需将这些标志添加到上面的命令中即可(将 X.XX 替换为您想要的相应 glibc 版本):

--passC:"-target x86_64-linux-gnu.X.XX -fno-sanitize=undefined" \
--passL:"-target x86_64-linux-gnu.X.XX -fno-sanitize=undefined" \

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM