2017-01-08 3 views
0

src/フォルダに3つのファイル:main.rs,lib.rscfgtools.rsがあります。私はcfgtools.rsを輸入したいと思います。ルースをインポートすると失敗します

main.rs

pub mod cfgtools; 

cfgtools.rs

pub fn get_os() -> &'static str { 
     let mut sys:&'static str = "unknown"; 
     if cfg!(target_os = "windows") { sys = "windows" }; 
     if cfg!(target_os = "macos")  { sys = "macos" }; 
     if cfg!(target_os = "ios")  { sys = "ios" }; 
     if cfg!(target_os = "linux")  { sys = "linux" }; 
     if cfg!(target_os = "android") { sys = "android" }; 
     if cfg!(target_os = "freebsd") { sys = "freebsd" }; 
     if cfg!(target_os = "dragonfly") { sys = "dragonfly" }; 
     if cfg!(target_os = "bitrig") { sys = "bitrig" }; 
     if cfg!(target_os = "openbsd") { sys = "openbsd" }; 
     if cfg!(target_os = "netbsd") { sys = "netbsd" }; 
     return sys; 
} 

はそれでも、私はエラーを取得する

extern crate cfgtools; 

use cfgtools::*; 

fn main() { 
    let os = get_os(); 
    println!("Your OS: {}",os); 
} 

lib.rs:

Compiling sys_recog v0.1.0 (file:///home/sessho/rust/sys_recog) 
error[E0463]: can't find crate for `cfgtools` 
    --> main.rs:17:1 
    | 
17 | extern crate cfgtools; 
    | ^^^^^^^^^^^^^^^^^^^^^^ can't find crate 

私はRustとこのコンセプトをインポートするのが新しいです。

+0

どのようにコンパイルしますか?あなたの端末ではどんなコマンドを実行しますか? –

+0

これは単に 'cargo build'です。 – Sessho

+0

'Cargo.toml'を含むように質問を編集できますか? :)(PS:StackOverflowプロフェッショナル:誰かに通知したい場合は、あなたのコメントに@UserNameを書き留めてください!) –

答えて

4

ここで問題となるのは、クレートとモジュールの混乱です。あなたのソースファイルはすべて同じクレートのモジュールです。 lib.rsは不要で、cfgtoolsモジュールがほしいと思うようです。 extern crateは、別々に保管されている他のライブラリをインポートするために使用されます。貨物がそれらを見つけることができるように、externの箱もCargo.tomlに宣言する必要があります。

だから、このようなものでなければなりません:私は、新しい空白の作成にcargo init --bin .src/にそれらのファイルを置く

// Note pub to make it visible outside the module 
pub fn foo() { 
    println!("Hello, world!"); 
} 

main.rs

// Declare the module, which will be there as cfgtools.rs in the same directory. 
mod cfgtools; 

// Make things in cfgtools visible. Note that wildcard imports 
// aren't recommended as they can make it confusing to find where 
// things actually come from. 
use cfgtools::foo; 

// and use it: 
fn main() { 
    foo(); 
} 

cfgtools.rsクレート、cargo runプリントメッセージを出してください。

関連する問題