What Actually Portable Executable hello world in zig would look like?

I’d like to write a program in Zig to run on Linux, Mac and Windows using Cosmopolitan Lib C: Cosmopolitan Libc: build-anywhere run-anywhere C library

I tried zig build-obj to complie a simple Hello World into a main.o ELF (both amd64 and aarch64) file and then called Cosmo linker to glue things together but it did not work.

I could share my code and commands but I know so little of zig that I’m pretty sure they don’t won’t add much. My end goal is to write a tiny wrapper for a cli tool. This wrapper runs on any OS, it downloads the correct CLI from GitHub, unpacks and runs it.

1 Like

I would start with understanding what cosmocc does under the hood (e.g. which target-triple it is using):

…and then try to replicate those exact compilation settings in the Zig compiler (my uneducated guess is that it’s mainly about making sure that the Zig-compiled code uses the same target triple expected by the cosmo-linker).

PS: also this ‘fixupobj’ command in the link above seems kinda important…, don’t know what this does though.

PS: this older thread might also be relevant: Actually Portable Executable (APE) with Zig

2 Likes

I captured cosmocc commands in scratch/sample/make.log at hello-zig-ape · igorgatis/scratch · GitHub

And I tried to replicate them here: scratch/Makefile at hello-zig-ape · igorgatis/scratch · GitHub

Notice that I even tried:

  1. `-target x86_64-linux-musl` and `-target arch64-linux-musl` => Segmentation fault
  2. `-target x86_64-freestanding` and `-target aarch64-freestanding` => prints `usage: tr [-Ccs] string1 string2`

Sounds like I need something like `-target x86_64-cosmo-libc` and `-target aarch64-cosmo-libc` or similar but I have no idea what needs to be done.

Welcome to Ziggit @igorgatis!

Sounds cool. @flooh linked to the only thread on APE and Zig I’ve seen, I suspect you’re pretty far off the beaten path with this one.

I’d suggest getting to know the language and build system a bit better first, link in some C libraries, call them from Zig, and then take another crack at adding the more exotic Cosmopolitan build.

Be sure to tell us how it works once you figure it out :slight_smile:

I think your best bet is to compile your code to C, then you just run the cosmo toolchain lile any other C program.