Skip to content

Cargo reference build script example fails to compile #15289

@ostkamp

Description

@ostkamp

Problem

contains the following lines:

extern { fn hello(); }

fn main() {
    unsafe { hello(); }
}

This does not or no longer compile with rust 1.85.0. Obviously it is not / no longer sufficient to have an unsafe keyword just around the location where it gets called. It needs to be on an extern statement as well.

   Compiling hello-world-from-c v0.1.0 (/home/ostkamp/rust/projects/14_More_about_Cargo_and_Crates.io/hello-world-from-c)
error: extern blocks must be unsafe
 --> src/main.rs:3:1
  |
3 | extern { fn hello(); }
  | ^^^^^^^^^^^^^^^^^^^^^^

error: could not compile `hello-world-from-c` (bin "hello-world-from-c") due to 1 previous error

Steps

No response

Possible Solution(s)

Suggested solution: Change the extern line as outlined below:

unsafe extern "C" { fn hello(); }

// Note the lack of the `#[link]` attribute. We’re delegating the responsibility
// of selecting what to link over to the build script rather than hard-coding
// it in the source file.

fn main() {
    unsafe { hello(); }
}

Notes

The missing "unsafe" on "extern" statements may also apply to other examples within the same file.

Version


Metadata

Metadata

Assignees

No one assigned

    Labels

    A-documenting-cargo-itselfArea: Cargo's documentationC-bugCategory: bugE-easyExperience: EasyS-acceptedStatus: Issue or feature is accepted, and has a team member available to help mentor or review

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions