From 58e1ea72779e3aa76302a5123bc6faefde39c929 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20=22xq=22=20Quei=C3=9Fner?= Date: Sat, 23 Sep 2023 23:58:17 +0200 Subject: [PATCH] Implements usage of avr-gcc --- build.zig | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/build.zig b/build.zig index 19ba076..7ba08a5 100644 --- a/build.zig +++ b/build.zig @@ -26,6 +26,7 @@ pub const chips = struct { }, }, .hal = hal, + .binary_post_process = compileWithAvrGcc, }; }; @@ -40,6 +41,7 @@ pub const boards = struct { .url = "https://docs.arduino.cc/hardware/nano", .source_file = path("/src/boards/arduino_nano.zig"), }, + .binary_post_process = compileWithAvrGcc, }; pub const uno_rev3 = .{ @@ -51,11 +53,50 @@ pub const boards = struct { .url = "https://docs.arduino.cc/hardware/uno-rev3", .source_file = path("/src/boards/arduino_uno.zig"), }, + .binary_post_process = compileWithAvrGcc, }; }; }; -pub fn build(b: *std.build.Builder) void { +fn compileWithAvrGcc(b: *std.Build, c_file: std.Build.LazyPath) std.Build.LazyPath { + const compile_step = @fieldParentPtr(std.Build.CompileStep, "step", c_file.generated.step); + if (compile_step.target.ofmt != .c) { + // sanity check: if not building a C file, skip. + return c_file; + } + + const prog = b.findProgram(&.{"avr-gcc"}, &.{}) catch @panic("Please install avr-gcc!"); + + const lib_dir = if (b.zig_lib_dir) |lib_dir| + lib_dir.getPath(b) + else + b.pathJoin(&.{ std.fs.path.dirname(std.fs.path.dirname(b.zig_exe).?).?, "lib" }); + + const linker_script = compile_step.linker_script.?; + + const compiler = b.addSystemCommand(&.{ + prog, + "-g", // debug options + "-mmcu=avr5", // compile for avr5 + "-Wno-builtin-declaration-mismatch", // hide weird zig warnings + "-I", + lib_dir, + "-nostartfiles", // do not link _start from avrlibc + "-ffreestanding", // do not link libc + }); + + compiler.addArg("-T"); + compiler.addFileArg(linker_script); + + compiler.addArg("-o"); + const elf_file = compiler.addOutputFileArg("firmware.elf"); + + compiler.addFileArg(c_file); + + return elf_file; +} + +pub fn build(b: *std.Build) void { _ = b; // const optimize = b.standardOptimizeOption(.{}); // inline for (@typeInfo(boards).Struct.decls) |decl| {