Zig

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Zig and the translation is 43% complete.
Outdated translations are marked like this.
Other languages:

Zig is a general-purpose programming language and toolchain for maintaining robust, optimal and reusable software.

Zig positions itself as a modern alternative to C language, with greater expressiveness, enhanced safety, and increased power — in some areas operating at an even lower level than C.

Official Zig toolchain from Zig Software Foundation contains:

  • compiler, formatter, and test runner for Zig code,
  • compiler for C, C++ and Objective-C code; and automatic translator from C to Zig (based on Clang or own Aro compiler),
  • build system, which integrates all tools above in one package and targets pure-Zig, pure-C/C++, or mixed projects.


Thanks to the last 2 points, Zig has easy interoperability with libraries and programs that have C ABI support, and can call or define C functions without FFI.

Telepítés

Előfeltételek

Note
TODO: Ismertesse, hogy miként fordítható a Zig egy WASM transzpileren keresztül C nyelvre, és hogyan reprodukálható a WASM seed binárisok nélkül (látszólag Guix által való használatra [1]).

A Zig legalább a Linux kernel 3.16+ verzióját támogatja.[2] Ha forráskódból építik, akkor ugyanazzal a forráskódfordítóval kell lefordítani, mint az LLVM/Clang, ellenkező esetben problémák merülhetnek fel (részletek az alábbi Hibaelhárítás szakaszban).

USE jelölőzászlók

USE flags for dev-lang/zig A robust, optimal, and maintainable programming language

+llvm Build with LLVM backend and extensions enabled.
debug Build with debug extensions enabled.
doc Add extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally
verify-sig Verify upstream signatures on distfiles

USE flags for dev-lang/zig-bin A robust, optimal, and maintainable programming language

doc Add extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally
verify-sig Verify upstream signatures on distfiles

Choosing variant

Gentoo repository provides two package variants for the Zig toolchain. Both provide latest tagged releases, as well as versions specific to each variant.

All Zig versions are slotted and can be installed side-by-side if needed.

dev-lang/zig: based on official source code. Recommended:

  • For users who need more configurability, such as enabling compiler debugging to investigate crashes or contribute fixes upstream.
  • When required version of the LLVM suite is already installed.
  • If nightly version (9999) is needed.

dev-lang/zig-bin: based on official binaries. Recommended:

  • For users who don't want to spend time building Zig and/or LLVM suite.
  • If version with old async/await implementation (0.10.1) is needed.
Tip
If LLVM compiling is deemed too long, but compiling Zig itself is acceptable, user can try to enable Gentoo binary host and use pre-built LLVM.

Alternatively, llvm USE-flag can be disabled for dev-lang/zig instead.

However, note that not all architectures or packages support it. At the moment of writing, it's limited to x86-64 architecture.

Emerge

Így már települ a szoftvercsomag az emerge segítségével:

root #emerge --ask dev-lang/zig
Note
Cserélje le a dev-lang/zig szoftvercsomagot a dev-lang/zig-bin szoftvercsomagra annak érdekében, hogy a Zig bináris szoftvercsomagját használja.

Beállítás

Environment variables

All ebuilds that inherit from zig.eclass or zig-utils.eclass use following environment variables to configure build process:

Note
It's recommended to not touch these variables unless a specific need arises. Default values should be good enough for any system:
  • ZIG_TARGET: auto-detect by Zig, or follow CHOST and CFLAGS.
  • ZIG_CPU: follow CFLAGS and CHOST.
  • ZBS_ARGS_EXTRA: follow MAKEOPTS for job thread count, compile with ReleaseSafe optimization mode.

ZIG_TARGET

ZIG_TARGET specifies the Zig target tuple. It's closest analog from C toolchains is CHOST.

It corresponds to -Dtarget option in zig build or -target option in zig build-exe.

By default it's set to native (enables auto-detection by Zig). If cross-compiling is enabled, zig-utils.eclass tries to make correct value by converting content of CHOST and CFLAGS to ZIG_TARGET format.

It's recommended to not change this variable and let it follow C settings, unless translation by eclass or auto-detection by Zig fails.

FILE /etc/portage/make.conf/zigSetting ZIG_TARGET
# General format:
<arch>-<os>-<abi>
# Optionally, after <os> and <abi> their version can be specified.
 
# Let Zig detect automatically for host
ZIG_TARGET="native"
 
# Linux x86-64 system, with glibc
ZIG_TARGET="x86_64-linux-gnu"
# With versions limit (Linux kernel 6.1.12+ and glibbc 2.38+)
ZIG_TARGET="x86_64-linux.6.1.12...6.6.16-gnu.2.38"
 
# Linux PPC64 little-endian system, with musl
ZIG_TARGET="powerpc64le-linux-musl"

ZIG_CPU

ZIG_CPU specifies the Zig target CPU. It's closest analog from C toolchains is CFLAGS (part with -march, -mcpu and other flags).

It corresponds to -Dcpu option in zig build or -mcpu option in zig build-exe.

By default zig-utils.eclass tries to make correct value by converting content of CFLAGS and CHOST to ZIG_CPU format.

It can be changed safely at any time, but it's still recommended to let it be auto-filled by eclass using C environment variables.

FILE /etc/portage/make.conf/zigSetting ZIG_CPU
# General format:
<cpu>
# Optionally, after <cpu> list of enabled and disabled features can be specified.
# + means it is enabled, and - means disabled.
 
# Let Zig detect automatically for host
ZIG_CPU="native"
 
# AMD Zen 2 processor
ZIG_CPU="znver2"
# Generic x86-64 processor, supporting X87 instructions, but not SSE2
ZIG_CPU="x86_64+x87-sse2"

ZBS_ARGS_EXTRA

ZBS_ARGS_EXTRA specifies additional arguments passed to zig build. It's closest analog from C toolchains is MAKEOPTS and CFLAGS (part with -O flags).

By default it is empty, and eclass tries to get job count (like -j8) from MAKEOPTS. If ZBS_ARGS_EXTRA is set, eclass will try to get job count from it instead.

FILE /etc/portage/make.conf/zigSetting ZBS_ARGS_EXTRA
# By default, ebuilds will use ReleaseSafe optimization mode (analog of -O2).
 
# Allow using up to 8 threads and compile in ReleaseSmall if possible (analog of -Os)
ZBS_ARGS_EXTRA="-j8 --release=small"
# Compile in Debug if possible (analog of -Og) 
ZBS_ARGS_EXTRA="--release=none"

Alapértelmezett slot beállítása

Az eselect parancs használható a /usr/bin/zig szimbolikus link módosítására.

user $eselect zig help
Manage Zig versions
Usage: eselect zig <action> <options>
Standard actions:
  help                      Display help text
  usage                     Display usage information
  version                   Display version information
Extra actions:
  list                      List available Zig versions
  set <target>              Set active Zig version
    target                    Target name or number (from 'list' action)
  show                      Show current Zig version
  update                    Automatically update the zig symlink
    ifunset                   Do not override currently set version
user $eselect zig list
Available Zig versions:
  [1]   zig-0.10.1 *
  [2]   zig-bin-0.10.1

Használat

Optimize modes

Zig has 4 optimize modes, which define how final binary should be optimized, in same manner as -O options from CFLAGS:

Feature Debug (default for Zig) ReleaseSafe (default for eclass) ReleaseFast ReleaseSmall
Forráskódfordításnak a sebessége Gyors Lassú Lassú Lassú
biztonsági ellenőrzések futásidőben. Engedélyezve Letiltva Engedélyezve Letiltva
Optimizations Letiltva Sebességre optimalizálva Sebességre optimalizálva Méretre optimalizálva
Reprodukálható Nem garantált Igen Igen Igen
Egyenértékű a C nyelvben

(interoperabilitás vagy forráskódfordítás)[3].

-D_DEBUG -O0 -DNDEBUG -O2 -O2 -D_FORTIFY_SOURCE=2 -DNDEBUG -Os
-O0 -D_DEBUG -O2 -D_FORTIFY_SOURCE=2 -O2 -DNDEBUG -Os -DNDEBUG

For Gentoo ebuilds, ReleaseSafe is used by default, unless user, ebuild or project set their own preferences.

Note
A futásidejű biztonsági ellenőrzéseket felül lehet írni adott hatókörön vagy blokkon belül a @setRuntimeSafety beállításával. A forráskódfordítási időben végzett biztonsági ellenőrzések mindig engedélyezve vannak.

IDE and editor support

Most of editors and IDEs plugins for Zig leverage unofficial language server called ZLS. It is available as dev-zig/zls package in GURU repository.

For installing follow this guide to enable GURU repository, accept testing branch for this package and run:

root #emerge --ask dev-zig/zls::guru

After that visit this list of tools collected by upstream.

Önállóan

A felhasználó érdemes lehet megnézni a Using Zig to build a bare metal RISCV32 binary és Build an IoT App with Zig and LoRaWAN című bejegyzéseket.

Authoring ebuilds

For creating ebuilds with Zig-written programs or libraries it is highly recommended to read documentation for Zig Build System, zig.eclass, and zig-utils.eclass.

After that read documentation of zig-ebuilder and install it. It is available as app-portage/zig-ebuilder package in GURU repository.

Hibaelhárítás

"undefined reference to ..." üzenet jelenik meg az emerge munkája közben

A legvalószínűbb ok az, hogy az LLVM és Clang szoftvercsomagok más C++ forráskódfordítóval lettek összeállítva, mint a Zig. Győződjön meg róla, hogy a felhasználó ugyanazt a forráskódfordítót állította be, majd futtassa újra az forráskódnak a lefordítását.

warning: Encountered error: UnexpectedEndOfFile, falling back to default ABI and dynamic linker.

A Zig forráskódfordító a /usr/bin/env jelenlétére támaszkodik a libc kiválasztásához, amikor a host számítógépet célozza. Ellenőrzi, hogy a /usr/bin/env valódi ELF fájlt tartalmaz-e, vagy egy szimbolikus link/shebang-e egy másik végrehajtható fájlhoz, majd ezt a műveletet rekurzívan megismétli, amíg meg nem találja a valódi ELF fájlt. Ezután megpróbálja kinyerni a libc-ről szóló információkat ebből az ELF fájlból. Ha ez az üzenet megjelenik, akkor az azt jelenti, hogy a Zig nem tudta megfelelően felismerni azt, és ehelyett az alapértelmezett libc-t és ABI-t választja (például musl Linuxon). A megoldás az alábbi argumentumok használata a parancshoz:

user $zig build -Dtarget=<target>

Illetve:

user $zig build-exe -target <target>

Ahol a target a kívánt célarchitektúra, például native-native-gnu vagy native-native-musl. A célformátummal kapcsolatos további információkért tekintse meg a ZIG_MCPU és ZIG_TARGET szakaszt.

Eltávolítás

Unmerge

root #emerge --ask --depclean --verbose dev-lang/zig

További olvasnivaló a témában

  • C — a programming language developed for Bell Labs in the early 1970s
  • Clang — a C/C++/Objective-C/C++, CUDA, and RenderScript language front-end for the LLVM project
  • Rust — a general-purpose, multi-paradigm, compiled, programming language.
  • Go — an open source, statically typed, compiled programming language
  • Zig/Internals — describes how Zig compiles Zig source code into executable

Külső források

  • Hivatalos lista a közösségi terekről.
  • Hivatalos lista a közösségi projektekről és a fantasztikus-zig lista.
  • Ziglings — Tanulja meg a Zig nyelvet apró hibás programok javításával, a Rustlings által inspirálva.
  • Különbségek a zig cc és a clang között.

Hivatkozások