Skip to content

Instantly share code, notes, and snippets.

@sagehane
Last active July 3, 2025 03:56
Show Gist options
  • Select an option

  • Save sagehane/b990f2fda747aebdeb12735f9ac0a699 to your computer and use it in GitHub Desktop.

Select an option

Save sagehane/b990f2fda747aebdeb12735f9ac0a699 to your computer and use it in GitHub Desktop.
Demo for Zig's stack trace behaviour in C
void foo(int n);
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
void assert(bool ok);
size_t my_strlen(const char s[static 1]);
void bar(void);
void foo(int n) {
assert(n != 0);
puts("foo");
}
void baz(void) {}
int main(void) {
assert(my_strlen("foo") == sizeof("foo") - 1);
bar();
}
.PHONY: all clean fclean re
CC = zig cc
# `zig cc` passes `-fsanitize=undefined` by default.
CFLAGS = -Wall -Wextra -Werror -Wconversion #-fsanitize=undefined
SRC = main.c
OBJ = $(SRC:.c=.o) zig.o
demo : $(OBJ)
$(CC) $(CFLAGS) $(OBJ) -o $@
# `-lc` links to the system's libc found by `zig libc`. Also look at `zig env`.
# `-I<dir>` can be used to include files
# `-fcompiler-rt` is apprently needed in some cases (https://github.com/ziglang/zig/issues/7264)
# `-femit-h` would be nice but is broken as of writing (https://github.com/ziglang/zig/issues/23887)
zig.o : zig.zig include.h
zig build-obj -lc -I. $<
%.o : %.c
$(CC) -c $(CFLAGS) $< -o $@
all : demo
clean :
rm -f $(OBJ)
fclean : clean
rm -f demo
re : clean all
const std = @import("std");
const c = @cImport({
@cInclude("include.h");
});
export fn assert(ok: bool) void {
std.debug.assert(ok);
}
extern fn foo(n: c_int) void;
export fn bar() void {
c.foo(1);
foo(0);
}
export fn my_strlen(s: [*:0]const u8) usize {
var i: usize = 0;
while (s[i] != 0) : (i += 1) {}
return (i);
}
// With the following line, it becomes possible to run the program with the following command:
// ```
// $ zig run -I. -lc main.c zig.zig
// ```
pub const _start = void;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment