zig: First Program

csmcsm
2 min read

Overview:

A simple program that prints a message to the terminal.


Note:

I am showing you how to run a simple program, not a whole zig project setup(that will be covered later).


Steps:

  1. Create a folder 'hello' at a location of your choice. Mine is like this:
csm@csm:~/Documents/csm$ mkdir hello
  1. cd into it!
csm@csm:~/Documents/csm$ cd hello
csm@csm:~/Documents/csm/hello$
  1. Create a file main.zig and fill it with:
const std = @import("std");

pub fn main() !void {
    std.debug.print("Salutations to all masters!\n", .{});
}
  1. Open terminal in the hello project folder and run:

     csm@csm:~/Documents/csm/hello$ zig run main.zig
    

    Output:

Salutations to all masters!

Explanation:

  1. Our project 'hello' contains one zig source file:

    'main.zig'

    (Note: zig source files have .zig extension)

  2. Normally we compile our zig files into executable using zig's build command.

    But for getting started with zig, we are using a simple handy command called 'run' which simply compiles the specified file and runs it immediately(without creating a binary!).

  3. So, getting to the code in 'main.zig':

    1. First we import the standard library into a constant std (more on 'imports' later!)

    2. Then we have a main function which is the entry point of our program (just like in c).

      The !void means:

      • void means it returns no value.

      • !void means it returns no value but may return an error.

Spoiler alert: In this simple program we are using debug print which technically will not crash our program, so we don't need to say !void, we can just say void.

But, it is there for just getting used to it!

  1. We are using the print function, normally used for debugging, to print the message.(its a handy function to deal with in a simple program like this!)

    Arguments to print function:

    • First argument is the string we want to print.

    • Second is a zig struct (I know, its weird) which normally contains expressions which are used for formatting the string(more on that later!).

      For now, its empty! (No need for formatting in this program!).


Link to repo.


What we learned:

1. Zig has a weird struct syntax! (.{})
2. We can't get rid of the semicolans no matter which sys lang we choose
 (C,C++,Rust,Zig).
0
Subscribe to my newsletter

Read articles from csm directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

csm
csm