How can I override a constant via a compiler option?

后端 未结 2 682
挽巷
挽巷 2020-12-01 23:52

Is it possible to define a constant in source code that can be overridden by a compiler flag? That is, something like setting a #define value in the C preproces

2条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-02 00:30

    No, you can't define constants (read: const bindings) with a compiler flag. But you can use the env! macro for something similar. It reads some environment variable at compile time.

    const MAX_DIMENSIONS_RAW: &'static str = env!("MAX_DIMENSIONS");
    

    Sadly, this returns a string and not an integer. Furthermore we can't yet call arbitrary functions (like parse) at compile time to calculate a constant. You could use lazy_static to achieve something similar:

    lazy_static! {
        static ref MAX_DIMENSIONS: usize = MAX_DIMENSIONS_RAW.parse().unwrap();
    }
    

    Of course you should add proper error handling. If your user doesn't need to define the environment variable, you can use option_env!.

    With this approach, you can pass the setting at build time:

    $ MAX_DIMENSIONS=1000 cargo build
    

提交回复
热议问题