0

Now I have a project managed by Makefile. That is, make run is the entry for the project. Rust codes, managed by Cargo, is a part of my project.

What I want to achieve is to pass some arguments from Makefile to Rust codes.

I know how to achieve this in C:

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

So, I can just pass arguments from make run MYARGUMENT=xxx and in Makefile pass $(MYARGUMENT) to gcc.

How to achieve it if I want to pass MYARGUMENT to command cargo run?

Or, I kind of want a feature like this -- to disable some statements in Rust codes, which could be controlled from Makefile:

#ifdef XXX
printf("XXX is define!\n");
#endif
Yang_____
  • 117
  • 8
  • 1
    If you just want some conditional compilation, [cargo features](https://doc.rust-lang.org/cargo/reference/features.html) are your best bet. Though you can also [access environment variables](https://doc.rust-lang.org/stable/std/macro.env.html). So what is it you want to achieve? – Caesar Mar 13 '22 at 07:29
  • Are you sure you want to use makefiles and not plain Cargo? – Chayim Friedman Mar 13 '22 at 07:33
  • @ChayimFriedman Yes. I am using `cargo` to manage my codes. However, for the full project, `make run xxx=xxx` is the entry. Though I can make some changes in `.cargo/config`. – Yang_____ Mar 13 '22 at 07:36
  • Have you checked out [Conditional compilation - The Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html) and [How do I use conditional compilation with `cfg` and Cargo? - StackOverflow](https://stackoverflow.com/questions/27632660/how-do-i-use-conditional-compilation-with-cfg-and-cargo)? – Chayim Friedman Mar 13 '22 at 07:40
  • @Caesar Thanks! `cargo features` is exactly what I need. – Yang_____ Mar 13 '22 at 08:52

1 Answers1

0

Using gcc, you can use -D to specify a predefined macro and then use preprofessor directives to compile some code conditionally as below:

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

And pass -D to tell gcc a predefined macro: gcc -DDEBUG.

Using rustc, you can use cfg equivalently:

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

Then run rustc --cfg 'DEBUG' and you get the same result as gcc.

If you want to use cargo instead of use rustc directly, you can see this question: How do I use conditional compilation with cfg and Cargo?

Timothy Liu
  • 211
  • 1
  • 7