【发布时间】:2020-06-02 21:11:40
【问题描述】:
在我的 crate 中做某事的方法有好几种,有些会导致执行速度很快,有些二进制大小较小,有些还有其他优点,所以我为所有这些都提供了用户界面。未使用的函数将被编译器优化掉。我的 crate 中的内部函数也必须使用这些接口,我希望它们在编译时尊重用户的选择。
有像target_os这样的条件编译属性,它存储像linux或windows这样的值。如何创建这样的属性,例如prefer_method,以便我和用户可以使用它有点像下面的代码sn-ps?
我的箱子:
#[cfg(not(any(
not(prefer_method),
prefer_method = "fast",
prefer_method = "small"
)))]
compile_error("invalid `prefer_method` value");
pub fn bla() {
#[cfg(prefer_method = "fast")]
foo_fast();
#[cfg(prefer_method = "small")]
foo_small();
#[cfg(not(prefer_method))]
foo_default();
}
pub fn foo_fast() {
// Fast execution.
}
pub fn foo_small() {
// Small binary file.
}
pub fn foo_default() {
// Medium size, medium fast.
}
用户箱:
#[prefer_method = "small"]
extern crate my_crate;
fn f() {
// Uses the `foo_small` function, the other `foo_*` functions will not end up in the binary.
my_crate::bla();
// But the user can also call any function, which of course will also end up in the binary.
my_crate::foo_default();
}
我知道有 --cfg 属性,但 AFAIK 这些只表示布尔标志,而不是枚举值,当只有一个枚举值有效时,它允许设置多个标志。
【问题讨论】:
标签: rust conditional-compilation