Skip to content

Exercises

Exercise 16-1. Write a C file containing this function:

Exercise 16-1. Write a C file containing this function:

int add(int a, int b) {
    return a + b;
}

Write a Zig program that declares it with extern fn, calls it, and prints the result.

Exercise 16-2. Rewrite Exercise 16-1 using a header file and @cImport.

Exercise 16-3. Write a C function:

void greet(const char *name);

Call it from Zig. Use the correct Zig type for the string parameter.

Exercise 16-4. Import stdio.h and call puts from Zig.

Exercise 16-5. Export this Zig function:

export fn square(x: c_int) c_int {
    return x * x;
}

Call it from a C program.

Exercise 16-6. Define a C struct:

struct Point {
    int x;
    int y;
};

Define the matching Zig type with extern struct, pass it to Zig, and return x + y.

Exercise 16-7. Show why a Zig slice should not be exported directly to C. Rewrite the interface using pointer plus length.

Exercise 16-8. Build a Zig executable that links one C source file, one C header file, and one static library.

Exercise 16-9. Move all C linking options into build.zig.

Exercise 16-10. Write a small Zig wrapper around a C API. The exported C-shaped layer should be thin. The rest of the program should use ordinary Zig types.