Search code examples
rustlibccompile-time-constant

Why is `CMSG_SPACE` not a constant function in Rust?


According to the documentation:

pub const unsafe extern "C" fn CMSG_SPACE(length: c_uint) -> c_uint

However, if I compile

fn main() {
    let _ = [0u8; libc::CMSG_SPACE(1) as usize];
}

I get the following error:

error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
 --> src/bin/libc-const.rs:2:27
  |
2 |     let _ = [0u8; unsafe {libc::CMSG_SPACE(1) as usize}];
  |                           ^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0015`.

Solution

  • The const-extern-fn feature for libc is required to be active for this function to be const. The version documented on docs.rs has this feature enabled, which is why it is (unfortunately) shown as being const by default. This feature requires a nightly rustc.