LoginSignup
60
39

More than 5 years have passed since last update.

Rust:Cargoでmain.rs以外のソースファイルのmain()関数を実行する

Last updated at Posted at 2016-02-18

Cargo は、Rust のビルドシステム、兼、パッケージマネージャーです。cargo new ... --bin で実行可能アプリケーションのひな形を作成した後、cargo run でプログラムを実行しようとすると、デフォルトで src/main.rs の中の main() 関数が呼ばれます。

もし、別のソースファイルに書かれた main() 関数を実行したい時は、 Cargo.toml ファイルを編集して、bin ターゲットを追加します。

例えば、プロジェクトが以下のようになっていて、それぞれの mailN.rs ファイルの中で main() 関数が定義されている時は、

my_project
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── main1.rs
│   ├── main2.rs
│   └── main3.rs
└── target
    └── ...

Cargo.toml の [[bin]] 以下を、このように書きます:

Cargo.toml
[package]
name = ...
version = ...
authors = ...

[dependencies]
...

[[bin]]
name = "main1"
path = "src/main1.rs"

[[bin]]
name = "main2"
path = "src/main2.rs"

[[bin]]
name = "main3"
path = "src/main3.rs"

name が bin ターゲット名で、pathmain() 関数の書かれたソースファイルへの相対パスとなります。

そして、例えば、main2 を実行したい時は、以下のようにすれば OK です。

$ cargo run --bin main2

環境

以下のバージョンで確認:

  • cargo 0.8.0 (08da2f5 2015-12-21)
  • rustc 1.6.0

古いバージョンでも問題なく動くと思います。

60
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
60
39