authorgravatar for evan@lagerdata.comEvan Haas <evan@lagerdata.com> 2024-08-05 12:54:56-07:00
committergravatar for evan@lagerdata.comEvan Haas <evan@lagerdata.com> 2024-08-05 12:56:40-07:00
log4bdf04654e3bd8ac09882cb49595f6797f2f5d09
tree8c7ec69c6820197400ba83ac375524a1436df10e
parent724804a4e026eea8cd42804b44bb0449d4ab3f3c
signaturebadge-check Signed by SSH key SHA256:cf2/TFgSxv2uRX26INvFSw25Prr1Dy9H8MiRXgLpok4

tools: Add tool for checking size and alignment of C types

Prints _Static_asserts for the size and alignment of all the basic built-in C types. The output can be run through a compiler for the specified target to verify that Zig's values are the same as those used by a C compiler for the target.

1 files changed, 57 insertions(+), 0 deletions(-)

tools/generate_c_size_and_align_checks.zig created+57
...@@ -0,0 +1,57 @@
1//! Usage: zig run tools/generate_c_size_and_align_checks.zig -- [target_triple]
2//! e.g. zig run tools/generate_c_size_and_align_checks.zig -- x86_64-linux-gnu
3//!
4//! Prints _Static_asserts for the size and alignment of all the basic built-in C
5//! types. The output can be run through a compiler for the specified target to
6//! verify that Zig's values are the same as those used by a C compiler for the
7//! target.
8
9const std = @import("std");
10
11fn c_name(ty: std.Target.CType) []const u8 {
12 return switch (ty) {
13 .char => "char",
14 .short => "short",
15 .ushort => "unsigned short",
16 .int => "int",
17 .uint => "unsigned int",
18 .long => "long",
19 .ulong => "unsigned long",
20 .longlong => "long long",
21 .ulonglong => "unsigned long long",
22 .float => "float",
23 .double => "double",
24 .longdouble => "long double",
25 };
26}
27
28var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
29
30pub fn main() !void {
31 const gpa = general_purpose_allocator.allocator();
32 defer std.debug.assert(general_purpose_allocator.deinit() == .ok);
33
34 const args = try std.process.argsAlloc(gpa);
35 defer std.process.argsFree(gpa, args);
36
37 if (args.len != 2) {
38 std.debug.print("Usage: {s} [target_triple]\n", .{args[0]});
39 std.process.exit(1);
40 }
41
42 const query = try std.Target.Query.parse(.{ .arch_os_abi = args[1] });
43 const target = try std.zig.system.resolveTargetQuery(query);
44
45 const stdout = std.io.getStdOut().writer();
46 inline for (@typeInfo(std.Target.CType).Enum.fields) |field| {
47 const c_type: std.Target.CType = @enumFromInt(field.value);
48 try stdout.print("_Static_assert(sizeof({s}) == {d}, \"\");\n", .{
49 c_name(c_type),
50 target.c_type_byte_size(c_type),
51 });
52 try stdout.print("_Static_assert(_Alignof({s}) == {d}, \"\");\n\n", .{
53 c_name(c_type),
54 target.c_type_alignment(c_type),
55 });
56 }
57}