Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Extern crate declarations

Syntax
ExternCrateextern crate CrateRef AsClause? ;

CrateRefIDENTIFIER | self

AsClauseas ( IDENTIFIER | _ )

An extern crate declaration specifies a dependency on an external crate.

The external crate is then bound into the declaring scope as the given identifier in the type namespace.

Additionally, if the extern crate appears in the crate root, then the crate name is also added to the extern prelude, making it automatically in scope in all modules.

The as clause can be used to bind the imported crate to a different name.

The external crate is resolved to a specific soname at compile time, and a runtime linkage requirement to that soname is passed to the linker for loading at runtime. The soname is resolved at compile time by scanning the compiler’s library path and matching the optional crate_name provided against the crate_name attributes that were declared on the external crate when it was compiled. If no crate_name is provided, a default name attribute is assumed, equal to the identifier given in the extern crate declaration.

The self crate may be imported which creates a binding to the current crate. In this case the as clause must be used to specify the name to bind it to.

Three examples of extern crate declarations:

extern crate pcre;

extern crate std; // equivalent to: extern crate std as std;

extern crate std as ruststd; // linking to 'std' under another name

When naming Rust crates, hyphens are disallowed. However, Cargo packages may make use of them. In such case, when Cargo.toml doesn’t specify a crate name, Cargo will transparently replace - with _ (Refer to RFC 940 for more details).

Here is an example:

// Importing the Cargo package hello-world
extern crate hello_world; // hyphen replaced with an underscore

Underscore Imports

An external crate dependency can be declared without binding its name in scope by using an underscore with the form extern crate foo as _. This may be useful for crates that only need to be linked, but are never referenced, and will avoid being reported as unused.

The macro_use attribute works as usual and imports the macro names into the macro_use prelude.

The no_link attribute may be applied to an extern crate item to prevent linking the crate.

Note

This is helpful, e.g., when only the macros of a crate are needed.

Example

#[no_link]
extern crate other_crate;

other_crate::some_macro!();

The no_link attribute uses the MetaWord syntax and so does not accept any arguments.

The no_link attribute may only be applied to an extern crate declaration.

Note

rustc currently accepts and ignores the attribute in other positions but lints against it. This may become a hard error in the future.

Duplicate instances of the no_link attribute are ignored.

Note

rustc lints against duplicate use of this attribute.