"zig cc" Cross-Compiler

From OSDev.wiki
Revision as of 22:03, 22 April 2020 by osdev>Wesleyac (Add first draft of zig cc page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

If you want to write an operating system in C, you'll need a cross-compiler. However, building a GCC cross-compiler can be painful. If you just want to write C (not C++), you can use zig cc - a C cross-compiler that comes with the Zig programming language. There are pre-compiled binaries for Windows, Linux, MacOS, and FreeBSD.

Bare-Bones with zig cc

This section describes how to build Bare Bones using zig cc. First off, install the following software:

  • Zig (tested with version 0.6.0)
  • a modern gcc toolchain (if ld --version reports "GNU ld", you should be good to go)
  • NASM

If you want to complete Bare Bones with zig cc, you should use the boot.asm file provided in Bare Bones with NASM instructions (since Zig does not come with an assembler, just a C compiler). At that point, you can continue with Bare Bones, but instead of using i686-elf-gcc, use the following command to build kernel.c:

zig build-obj --c-source kernel.c -target i386-freestanding

This should create a kernel.o file, just the same as if you had used gcc.

When you get to the linking step, we won't be able to use i686-elf-gcc, but luckily, modern versions of GNU ld are able to emulate almost any other linker, so we can use the system ld like so:

ld -m elf_i386 -T linker.ld -o myos.bin boot.o kernel.o

And at that point, you can carry on with Bare Bones, and you should have an operating system, compiled without having to compile your own cross-compiler!