From 34e74f4bb36b0866be94c9bfdb41c11270b448a7 Mon Sep 17 00:00:00 2001 From: Jorge Aparicio Date: Sun, 16 Dec 2018 20:56:57 +0100 Subject: [PATCH] book: add an example of conditional compilation of resources and tasks --- book/src/by-example/tips.md | 14 ++++++++++ ci/script.sh | 2 ++ examples/cfg.rs | 54 +++++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 examples/cfg.rs diff --git a/book/src/by-example/tips.md b/book/src/by-example/tips.md index c1633288ed..5057c80af4 100644 --- a/book/src/by-example/tips.md +++ b/book/src/by-example/tips.md @@ -20,6 +20,20 @@ rewrite code. If you consistently use `lock`s to access the data behind shared resources then your code will continue to compile when you change the priority of tasks. +## Conditional compilation + +You can use conditional compilation (`#[cfg]`) on resources (`static [mut]` +items) and tasks (`fn` items). The effect of using `#[cfg]` attributes is that +the resource / task will *not* be injected into the prelude of tasks that use +them (see `resources`, `spawn` and `schedule`) if the condition doesn't hold. + +The example below logs a message whenever the `foo` task is spawned, but only if +the program has been compiled using the `dev` profile. + +``` rust +{{#include ../../../examples/cfg.rs}} +``` + ## Running tasks from RAM The main goal of moving the specification of RTFM applications to attributes in diff --git a/ci/script.sh b/ci/script.sh index 0244c58171..27229a5476 100644 --- a/ci/script.sh +++ b/ci/script.sh @@ -68,6 +68,8 @@ main() { generics ramfunc + + cfg ) for ex in ${exs[@]}; do diff --git a/examples/cfg.rs b/examples/cfg.rs new file mode 100644 index 0000000000..3f4ca90431 --- /dev/null +++ b/examples/cfg.rs @@ -0,0 +1,54 @@ +//! examples/cfg.rs + +#![deny(unsafe_code)] +#![deny(warnings)] +#![no_main] +#![no_std] + +extern crate panic_semihosting; + +#[cfg(debug_assertions)] +use cortex_m_semihosting::hprintln; +use rtfm::app; + +#[app(device = lm3s6965)] +const APP: () = { + #[cfg(debug_assertions)] // <- `true` when using the `dev` profile + static mut COUNT: u32 = 0; + + #[init] + fn init() { + // .. + } + + #[task(priority = 3, resources = [COUNT], spawn = [log])] + fn foo() { + #[cfg(debug_assertions)] + { + *resources.COUNT += 1; + + spawn.log(*resources.COUNT).ok(); + } + + // this wouldn't compile in `release` mode + // *resources.COUNT += 1; + + // .. + } + + #[cfg(debug_assertions)] + #[task] + fn log(n: u32) { + hprintln!( + "foo has been called {} time{}", + n, + if n == 1 { "" } else { "s" } + ) + .ok(); + } + + extern "C" { + fn UART0(); + fn UART1(); + } +};