sin(), cos(), log10() (float) not found for target thumbv7em-none-eabihf

Viewed 773

I'm using Rust 1.51 and this minimal crate:

#![no_std]

fn main() {
    let a = 2.0.cos();
}

I'm building it with cargo check --target thumbv7em-none-eabihf and the compiler complains with this message: no method named 'cos' found for type '{float}' in the current scope. Same for sin() and log10().

I found https://docs.rust-embedded.org/cortex-m-quickstart/cortex_m_quickstart/ and I would expect the above message for targets thumbv6m-none-eabi or thumbv7em-none-eabi but not for thumbv7em-none-eabihf which has FPU support.

How can I solve this?

2 Answers

In Rust 1.51 (and below) functions like sin, cos, or log10 are not part of the core library (core::) but only the standard library (std::), therefore they are not available.

A practical solution is to use the crate libm which offers typical mathematic functions for no_std-environments.

#![no_std]

fn main() {
    let a = libm::cosf(2.0);
}

See:

What @phip1611 said is correct, cos is no longer part of the core library and hence not usable in no_std out of the box. You can use libm directly OR via a std friendly wrapper using the num-traits crate with the libm feature enabled. This lets you write no_std code as you would write std code. E.g.

# cargo.toml
num-traits = { version = "0.2", default-features = false, features = ["libm"] }

And then in your code:

#![no_std]

#[allow(unused_imports)]
use num_traits::real::Real;

fn main() {
    let a = 2.0.cos();
}
Related