I've tried reading various github issues trying to track down what the difference is and just ended up confused.
#[no_mangle]
pub extern fn foo() {
...
}
vs.
#[no_mangle]
pub extern "C" fn foo() {
...
}
The extern keyword is used in two places in Rust. One is in conjunction with the crate keyword to make your Rust code aware of other Rust crates in your project, i.e., extern crate lazy_static; . The other use is in foreign function interfaces (FFI). extern is used in two different contexts within FFI.
extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.
This module provides utilities to handle data across non-Rust interfaces, like other programming languages and the underlying operating system. It is mainly of use for FFI (Foreign Function Interface) bindings and code that needs to exchange C-like strings with other languages.
Rust can link to/call C functions via its FFI, but not C++ functions. While I don't know why you can't call C++ functions, it is probably because C++ functions are complicated. You can just define C linkage on any C++ function, making it available from C and thus also Rust. extern "C" is your friend here.
There is no difference because, as the reference says:
By default external blocks assume that the library they are calling uses the standard C ABI on the specific platform.
extern "C"
-- This is the same asextern fn foo();
whatever the default your C compiler supports.
An issue was created to always require explicitly stating extern "C"
but the RFC has been refused.
There is an issue in fmt-rfcs about "should we format extern "C" fn
as that or extern fn
?".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With