Change defineCMacro to take separate name and value arugments

Before this change, when one or more of name or value are not known at
comptime, build.zig files must allocate and do the concatanation, which can be
cumbersome, and also adds a redundant allocation when name and value are
slices. The new version only does a single allocation directly in the builder's
allocator to concatonate name and value.

The origional behavior is available in defineCMacroRaw, for use in situations
such as parseing c compiler arguments.

Additionally, several places have been updated to use the new funtions.
This commit is contained in:
Asa Zeren 2021-03-23 18:58:24 -04:00 committed by Veikka Tuominen
parent 0bde5ce369
commit 6cc8845802
2 changed files with 19 additions and 4 deletions

View File

@ -117,7 +117,7 @@ pub fn build(b: *Builder) !void {
// of being built by cmake. But when built by zig it's gonna get a compiler_rt so that
// is pointless.
exe.addPackagePath("compiler_rt", "src/empty.zig");
exe.defineCMacro("ZIG_LINK_MODE=Static");
exe.defineCMacro("ZIG_LINK_MODE", "Static");
const softfloat = b.addStaticLibrary("softfloat", null);
softfloat.setBuildMode(.ReleaseFast);

View File

@ -1700,8 +1700,23 @@ pub const LibExeObjStep = struct {
}
}
/// If the value is omitted, it is set to 1.
/// `name` and `value` need not live longer than the function call.
pub fn defineCMacro(self: *LibExeObjStep, name: []const u8, value: ?[]const u8) void {
var macro = self.builder.allocator.alloc(
u8,
name.len + if (value) |value_slice| value_slice.len + 1 else 0,
) catch |err| if (err == error.OutOfMemory) @panic("Out of memory") else unreachable;
mem.copy(u8, macro, name);
if (value) |value_slice| {
macro[name.len] = '=';
mem.copy(u8, macro[name.len + 1 ..], value_slice);
}
self.c_macros.append(macro) catch unreachable;
}
/// name_and_value looks like [name]=[value]. If the value is omitted, it is set to 1.
pub fn defineCMacro(self: *LibExeObjStep, name_and_value: []const u8) void {
pub fn defineCMacroRaw(self: *LibExeObjStep, name_and_value: []const u8) void {
self.c_macros.append(self.builder.dupe(name_and_value)) catch unreachable;
}
@ -1790,9 +1805,9 @@ pub const LibExeObjStep = struct {
self.linkSystemLibraryName(tok["-l".len..]);
} else if (mem.eql(u8, tok, "-D")) {
const macro = it.next() orelse return error.PkgConfigInvalidOutput;
self.defineCMacro(macro);
self.defineCMacroRaw(macro);
} else if (mem.startsWith(u8, tok, "-D")) {
self.defineCMacro(tok["-D".len..]);
self.defineCMacroRaw(tok["-D".len..]);
} else if (mem.eql(u8, tok, "-pthread")) {
self.linkLibC();
} else if (self.builder.verbose) {