Home Computing Introduction to Zig, a Potential Heir to C

Introduction to Zig, a Potential Heir to C

I haven’t used C for a long time. At the very start of my computing days, I would see machine code on an austere school computer. When my friends went on to write their early 8 bit games, they used assembly language. After a bit of BASIC, I graduated to C. (And then to C++)

Zig is the new C. But as you might have little or no use for what is now a low level language, this post only glimpses into the world that exists closer to the metal. The general advice for developers is to learn one language well, but understand the patterns and structures that will allow you to adopt any language you need.

Zig describes itself as a “general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.” When we use the term low level language, it just means you are fewer abstractions away from manipulating hexadecimal numbers directly in registers. They are tied more closely to how a computer actually functions moment to moment. And there are no ‘objects’.

A low level language is necessarily fast and probably small — then again, higher level languages are encumbered with internal management to make them easier to use. If speed or size is important to you, then you have to go low level. Many devices are technically “programmable” but cannot hold fully fledged operating systems. At some point in your career you may need to pump bits into a device that you can’t program with Java. The inventor of Zig, Andrew Kelley, was trying to work with audio devices in a music studio, and realised he would have to rewrite C libraries to add features he thought he needed.

Low level languages don’t handle memory management for you. This is now a bit of a Rubicon, as many developers have never had to allocate and release their own memory. The unreliable behaviour of garbage collectors on the other hand, is considered by low level programmers a good example of an encumbrance. And of course, C is not “object oriented”, so we refer to functions, not methods.

Zig is an entire build chain, and also a C compiler. C libraries are underneath many other languages, so Zig’s high degree of interoperability with C and C++ will improve its popularity. We can see this straight away.

Testing Zig

I first install Zig onto my trusty Mac:

If Zig is indeed a C compiler, then I should be able to build good old C code. The official “hello world” for C is this:

So we use the main function to define the ‘entry point’ for the executable. The parameters include the number of arguments (count), and a pointer to the set of command line arguments. At the top, we pull in a header that references the standard io commands, like printf.

As a quick refresher, if I want to build an executable I can run on my Mac, my build chain goes through these steps:

  • My C code meets the pre-processor, which adds the code from header files (those with the .h suffix), strips out comments and generally makes sure that you are left with plain code.
  • The compiler then turns the C code into assembler language, or an intermediate equivalent.
  • The assembler then creates “object code” or binary. We are now getting nearer.
  • Finally, the linker brings in all the library code needed to actually do anything useful on my machine.

And indeed, Zig did build my C executable:

(Ignore the time it took to build — my Mac is almost a decade old). Zig claims to be faster than C, but those types of claims are best examined in better technical detail for the area you need.

OK, that’s C. But what about “hello world” for Zig?

OK, this does look more modern. We import some type of reference to a ‘std’ library, which we use directly. The main is a public function that returns nothing. I guess ‘.{}’ means no extra arguments. And that debug function in the standard library probably allows use of the console. So lets build:

Yes, it just overwrote my C version of hello.

But here is the cool thing. Without extra tooling, I can cross compile to, say, Windows:

That is quite a thing. As Zig describes it, “Cross-compiling is a first-class use case”. (I haven’t tested this file on a Windows machine, so YMMV.)

But let’s take a look at what else Zig is offering.

Testing and Build Safety

Zig understands that debugging low-level code is treacherous, so it has various ways to combat this. Zig comes with a test runner and test block built in. This gives you a chance to isolate areas of concern:

This runs thusly:

We get a glimpse into the declaration of variables: the addOne functions expects a 32-bit integer and emits one in return.

Zig defines four build flags:

  • The standard Debug. This compiles quickly and enables safety checks, so sacrifices speed and size for testing convenience.
  • ReleaseFast. This optimizes for speed, but sacrifices compilation speed and size.
  • ReleaseSafe. For live testing, this keeps safety checks on.
  • ReleaseSmall. Keeps the binary small.

Naturally, a compile-time error message is considerably better to receive compared to the “undefined behavior” of a build with the training wheels off.

Do You Remember? Because Zig Doesn’t

The reason you aren’t using C right now is largely to do with its lack of memory management, as I’ve already mentioned. Low-level languages don’t have garbage collection, and leave you to clean up. Or crash. However, Zig does provide defer as an escape pod to fix things if they go awry:

So to start with, we are asking to allocate a page of memory straight off the heap. Then the alloc function tries to reserve an array of 100 unsigned 8-bit integers (u8). As this is in a test block, we can check that the array is indeed 100 long, and that it is indeed of type u8.

The defer statement is run immediately after the current scope is finished, however it finishes. So whatever happens with our allocation, memory is cleaned up. If, instead, the defer line ran immediately from its position in the code, the tests would all fail. But they don’t.

Race to the Bottom

So Zig is, if you like, trying to win the race to the bottom, to be the new underpinning of computing. The heir to C. It is also trying to be simpler (with fewer keywords) and a safer platform. The hidden comparison I appear to be making is with Rust, but they probably already have different audiences. Like Rust, Zig has a very active contributor community so is already guaranteed a future. But beware: simplicity is quite hard.

Group Created with Sketch.


 

Reference

Denial of responsibility! TechCodex is an automatic aggregator of Global media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, and all materials to their authors. For any complaint, please reach us at – [email protected]. We will take necessary action within 24 hours.
DMCA compliant image

Leave a Comment