Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between extern fn and extern "C" fn in Rust?

Tags:

rust

ffi

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() {
   ...
}
like image 789
marathon Avatar asked Jun 20 '17 23:06

marathon


People also ask

What does extern C do in Rust?

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.

What is extern C?

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.

What is FFI Rust?

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.

How do you call C function in Rust?

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.


1 Answers

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 as extern 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?".

like image 171
Stargateur Avatar answered Sep 29 '22 05:09

Stargateur