Skip to content

Commit f91ad44

Browse files
committed
Add docs on extern keyword
1 parent f15a1ec commit f91ad44

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/libstd/keyword_docs.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,48 @@ mod crate_keyword { }
179179
/// [Reference]: https://doc.rust-lang.org/reference/items/enumerations.html
180180
mod enum_keyword { }
181181

182+
#[doc(keyword = "extern")]
183+
//
184+
/// For external connections in Rust code.
185+
///
186+
/// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
187+
/// keyword to make your Rust code aware of other Rust crates in your project, i.e. `extern crate
188+
/// lazy_static;`. The other use is in foreign function interfaces (FFI).
189+
///
190+
/// `extern` is used in two different contexts within FFI. The first is in the form of external
191+
/// blcoks, for declaring function interfaces that Rust code can call foreign code by.
192+
///
193+
/// ```rust ignore
194+
/// #[link(name = "my_c_library")]
195+
/// extern "C" {
196+
/// fn my_c_function(x: i32) -> bool;
197+
/// }
198+
/// ```
199+
///
200+
/// This code would attempt to link with libmy_c_library.so on unix-like systems and
201+
/// my_c_library.dll on Windows at runtime, and panic if it can't find something to link to. Rust
202+
/// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with
203+
/// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.
204+
///
205+
/// The mirror use case of FFI is also done via the `extern` keyword:
206+
///
207+
/// ```rust
208+
/// # #![allow(private_no_mangle_fns)]
209+
/// #[no_mangle]
210+
/// pub extern fn callable_from_c(x: i32) -> bool {
211+
/// x % 3 == 0
212+
/// }
213+
/// ```
214+
///
215+
/// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the
216+
/// function could be used as if it was from any other library.
217+
///
218+
/// For more information on FFI, check the [Rust book] or the [Reference].
219+
///
220+
/// [Rust book]: https://doc.rust-lang.org/book/second-edition/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
221+
/// [Reference]: https://doc.rust-lang.org/reference/items/external-blocks.html
222+
mod extern_keyword { }
223+
182224
#[doc(keyword = "fn")]
183225
//
184226
/// The `fn` keyword.

0 commit comments

Comments
 (0)