From adc5bce5e8487cf9507ab5dd2b1b60dd7f54cc3d Mon Sep 17 00:00:00 2001 From: Vexu Date: Thu, 20 Aug 2020 10:08:27 +0300 Subject: translate-c: correct translation of global variables * externs with intializers are translated as exports * non extern without explicit initialization are zero initalized --- lib/std/mem.zig | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'lib/std') diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 1ba64f47fa..7f1b5ae618 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -221,9 +221,19 @@ pub fn zeroes(comptime T: type) T { .Vector => |info| { return @splat(info.len, zeroes(info.child)); }, + .Union => |info| { + if (comptime meta.containerLayout(T) == .Extern) { + // The C language specification states that (global) unions + // should be zero initialized to the first named member. + var item: T = undefined; + @field(item, info.fields[0].name) = zeroes(@TypeOf(@field(item, info.fields[0].name))); + return item; + } + + @compileError("Can't set a " ++ @typeName(T) ++ " to zero."); + }, .ErrorUnion, .ErrorSet, - .Union, .Fn, .BoundFn, .Type, @@ -312,6 +322,14 @@ test "mem.zeroes" { for (b.sentinel) |e| { testing.expectEqual(@as(u8, 0), e); } + + const C_union = extern union { + a: u8, + b: u32, + }; + + var c = zeroes(C_union); + testing.expectEqual(@as(u8, 0), c.a); } /// Sets a slice to zeroes. -- cgit v1.2.3