英文:
How to do conditional compilation with Zig?
问题
例如,我可以使用CMake为C/C++预处理器添加定义
add_definitions(-DFOO -DBAR ...)
然后我可以在条件编译中使用它们
#ifdef FOO
代码 ...
#endif
#ifdef BAR
代码 ...
#endif
是否可以通过编译参数或类似的方式在Zig及其构建系统中执行相同的操作?
英文:
For example, I can add definitions for C/C++ preprocessor with CMake
add_definitions(-DFOO -DBAR ...)
and then I can use them for conditional compilation
#ifdef FOO
code ...
#endif
#ifdef BAR
code ...
#endif
Is there a way to do the same thing with Zig and its build system using compilation arguments or something like that?
答案1
得分: 3
以下是翻译好的部分:
- 创建一个名为
build.zig
的单独文件,其中包含一个名为build()
的函数:
const std = @import("std");
pub fn build(b: *std.build.Builder) !void {
const build_options = b.addOptions();
// 添加命令行标志
// 并设置默认值
build_options.addOption(bool, "sideways", b.option(bool, "sideways", "print sideways") orelse false);
// 设置可执行文件名和源代码
const exe = b.addExecutable("hello", "hello.zig");
exe.addOptions("build_options", build_options);
// 编译并复制到 zig-out/bin
exe.install();
}
- 在名为
hello.zig
的单独文件中使用条件编译选项,使用@import("build_options")
:
const std = @import("std");
pub fn main() !void {
const print_sideways = @import("build_options").sideways;
const stdout = std.io.getStdOut().writer();
if (print_sideways) {
try stdout.print("Sideways Hello, {s}!\n", .{"world"});
} else {
try stdout.print("Regular Hello, {s}!\n", .{"world"});
}
}
- 使用以下命令进行编译:
zig build -Dsideways=true
- 执行
zig-out/bin/hello
将输出以下内容:
Sideways Hello, world!
英文:
You can do something similar using the build system. This requires some boilerplate code to do the option handling. Following the tutorial on https://zig.news/xq/zig-build-explained-part-1-59lf for the build system and https://ziggit.dev/t/custom-build-options/138/8 for the option handling:
- Create a separate file called
build.zig
that contains a functionbuild()
:
const std = @import("std");
pub fn build(b: *std.build.Builder) !void {
const build_options = b.addOptions();
// add command line flag
// and set default value
build_options.addOption(bool, "sideways", b.option(bool, "sideways", "print sideways") orelse false);
// set executable name and source code
const exe = b.addExecutable("hello", "hello.zig");
exe.addOptions("build_options", build_options);
// compile and copy to zig-out/bin
exe.install();
}
- Use the option for conditional compilation in a separate file
hello.zig
using@import("build_options")
:
const std = @import("std");
pub fn main() !void {
const print_sideways = @import("build_options").sideways;
const stdout = std.io.getStdOut().writer();
if (print_sideways) {
try stdout.print("Sideways Hello, {s}!\n", .{"world"});
} else {
try stdout.print("Regular Hello, {s}!\n", .{"world"});
}
}
- Compile with:
zig build -Dsideways=true
- Executing
zig-out/bin/hello
gives the following output:
Sideways Hello, world!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论