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 声明

Syntax
ExternCrateextern crate CrateRef AsClause? ;

CrateRefIDENTIFIER | self

AsClauseas ( IDENTIFIER | _ )

extern crate 声明指定对某个外部 crate 的依赖。

外部 crate 然后以给定的标识符绑定到声明所在的作用域的类型命名空间中。

此外,如果 extern crate 出现在 crate 根中,则该 crate 名称也会被添加到外部预导入中,使其自动在任何模块中可见。

as 子句可用于将导入的 crate 绑定到不同的名称。

外部 crate 在编译时解析为特定的 soname,并将对该 soname 的运行时链接要求传递给链接器,以便在运行时加载。soname 在编译时通过扫描编译器的库路径并匹配提供的可选 crate_name 与外部 crate 编译时声明的 crate_name 属性 来解析。如果没有提供 crate_name,则假定使用默认的 name 属性,该属性等于 extern crate 声明中给出的标识符

可以导入 self crate,这会创建对当前 crate 的绑定。在这种情况下必须使用 as 子句来指定绑定名称。

三个 extern crate 声明的示例:

extern crate pcre;

extern crate std; // 等价于: extern crate std as std;

extern crate std as ruststd; // 以其他名称链接到 'std'

在命名 Rust crate 时,不允许使用连字符。然而,Cargo 包可能会使用它们。在这种情况下,当 Cargo.toml 没有指定 crate 名称时,Cargo 会透明地将 - 替换为 _(详见 RFC 940)。

示例如下:

// 导入 Cargo 包 hello-world
extern crate hello_world; // 连字符被替换为下划线

下划线导入

可以使用下划线形式 extern crate foo as _ 声明外部 crate 依赖而不将其名称绑定到作用域中。这对于只需要链接但从不会被引用的 crate 很有用,并且可以避免被报告为未使用。

macro_use 属性照常工作,并将宏名称导入 macro_use 预导入中。

no_link 属性 可以应用于 extern crate 程序项,以阻止链接该 crate。

Note

例如,当只需要 crate 的宏时,这很有用。

Example

#[no_link]
extern crate other_crate;

other_crate::some_macro!();

no_link 属性使用 MetaWord 语法。

no_link 属性只能应用于 extern crate 声明。

Note

rustc 会忽略在其他位置的使用但会给出 lint 警告。这将来可能变成错误。

只有在 extern crate 声明上首次使用 no_link 才会生效。

Note

rustc 会对首次之后的任何使用给出 lint 警告。这将来可能变成错误。