如何将自定义参数从 Makefile 传递到 Cargo 中的 Rust 代码?

How to pass customized arguments from Makefile to Rust codes in Cargo?

现在我有一个项目由 Makefile 管理。也就是说,make run 是项目的条目。 Rust 代码,由 Cargo 管理,是我项目的一部分。

我想要实现的是将一些参数从Makefile传递给Rust代码。

我知道如何在 C 中做到这一点:

$ gcc --help | grep -- -D
  -D <macro>=<value>      Define <macro> to <value> (or 1 if <value> omitted)

所以,我可以只传递来自 make run MYARGUMENT=xxx 的参数,然后在 Makefile 中将 $(MYARGUMENT) 传递给 gcc

如何实现如果我想通过MYARGUMENT命令cargo run?

或者,我有点想要这样的功能——禁用 Rust 代码中的某些语句,这可以从 Makefile 中控制:

#ifdef XXX
printf("XXX is define!\n");
#endif

使用gcc,你可以使用-D指定一个预定义的宏,然后使用preprofessor指令有条件地编译一些代码如下:

int main(void)
{
#if defined(DEBUG_)
    printf("Debug mode\n");
#endif
}

并传递-D告诉gcc一个预定义的宏:gcc -DDEBUG.

使用rustc,可以等价地使用cfg

fn main() {
    #[cfg(DEBUG)]
    {
        println!("Debug mode");
    }
}

然后运行 rustc --cfg 'DEBUG' 你会得到与gcc相同的结果。

如果想使用cargo而不是直接使用rustc,可以看这个问题:How do I use conditional compilation with cfg and Cargo?