Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many lines are covered by the Rust conditional compilation attribute?

I'm trying to use a conditional compilation statement. Beyond defining a function that should only exist in a debug build, I want to define a set of variables/constants/types that only exist in the debug build.

#[cfg(debug)]
pub type A = B;
pub type B = W;

#[cfg(other_option)]
pub type A = Z;
pub type B = I;
let test = 23i32;

How many lines are actually "covered" by the conditional compile attribute in this case? Is it only one (what I would expect in this context)? Are there ways to ensure that a whole block of code (including variables, types and two functions) is covered by the condition?

like image 963
DerNils Avatar asked Sep 02 '16 11:09

DerNils


People also ask

What is meant by conditional compilation?

Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.

What is CFG rust?

Rust has a special attribute, #[cfg] , which allows you to compile code based on a flag passed to the compiler.


Video Answer


2 Answers

You can use a module to group together everything that should exist for debug/release only, like this:

#[cfg(debug)]
mod example {
    pub type A = i32;
    pub type B = i64;
}

#[cfg(not(debug))]
mod example {
    pub type A = u32;
    pub type B = u64;
}

fn main() {
    let x: example::A = example::A::max_value();
    println!("{}", x);
}

Playground link (note that this will always print the not(debug) value because the playground doesn't define the debug feature, even in debug mode).

If debug is defined, this will print 2147483647 (the maximum value of an i32), otherwise it will print 4294967295 (the maximum value of a u32). Keep in mind that both modules must have definitions for each item, otherwise you'll hit a compile-time error.

If you've not read about Attributes, it might be a good idea to do so; make sure you know the difference between inner attributes (#![attribute]) and outer attributes (#[attribute]).

like image 179
Aurora0001 Avatar answered Sep 28 '22 00:09

Aurora0001


An #[attribute] only applies to the next item. Please see the Rust book.

Edit: I don't think it is currently possible to spread an attribute over an arbitrary number of declarations.

Additional, in-depth information on attributes and their application can be found at Rust reference.

like image 27
ljedrz Avatar answered Sep 27 '22 23:09

ljedrz