Skip to content

Instantly share code, notes, and snippets.

@magurofly
Created April 5, 2024 16:17
Show Gist options
  • Save magurofly/3e6d53759ab67c0f0c82ca559d42957c to your computer and use it in GitHub Desktop.
Save magurofly/3e6d53759ab67c0f0c82ca559d42957c to your computer and use it in GitHub Desktop.
rustcでコンパイル時にライブラリをリンクする

rustc コマンドに --extern クレート名=rlibへのパス を渡すことでライブラリが use で使えるようになる。

rlib ファイルの作成

例: proconio-0.4.5 をコンパイルして rlib を作成する。

# proconio-0.4.5 を git clone する
git clone --depth 1 -b p-v0.4.5 https://github.com/statiolake/proconio-rs.git
# コンパイルする
cd proconio-rs/proconio
cargo rustc --release -- --crate-type=rlib --emit=link -C opt-level=3 -C embed-bitcode=no
cd ../..
# proconio-rs/target/release/libproconio.rlib が作成される

rlib ファイルのリンク

echo 'fn main() { proconio::input!(s: String); println!("Hello, {s}!"); }' > main.rs
rustc --crate-name=main --edition=2018 --crate-type=bin --emit=link -C opt-level=3 -C embed-bitcode=no --extern proconio=proconio-rs/target/release/libproconio.rlib main.rs
# ./main が作成される
echo World | ./main
#=> Hello, World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment