从这个源代码开始:
fn main() {
println!("Hello, world!");
}
您可以创建 LLVM 中间表示 (IR) 或 bitcode (BC):
# IR in hello.ll
rustc hello.rs --emit=llvm-ir
# BC in hello.bc
rustc hello.rs --emit=llvm-bc
这些文件随后可以由 LLVM 进一步处理以生成 程序集 或 目标文件:
# Assembly in hello.s
llc hello.bc
# Object in hello.o
llc hello.bc --filetype=obj
然后您需要链接文件以生成可执行文件。这需要链接到 Rust 标准库。路径取决于平台和版本:
cc -L/path/to/stage2/lib/rustlib/x86_64-apple-darwin/lib/ -lstd-f4a73f2c70e583e1 -o hello2 hello.o
然后你就可以运行程序了:
DYLD_LIBRARY_PATH=/path/to/stage2/lib/rustlib/x86_64-apple-darwin/lib/ ./hello2
这个答案有 macOS 特定的解决方案,但一般概念应该可以扩展到 Linux 和 Windows。 Linux 的实现会略有不同,Windows 的实现可能会有很大差异。值得注意的是,我使用的是DYLD_LIBRARY_PATH,因为我已经动态链接到不在我通常的库搜索路径中的 Rust 标准库。
请注意,LLVM IR 和 BC 文件没有最强的向前/向后兼容性保证。这意味着您需要使用与您正在使用的rustc 版本兼容的llc 版本。对于这个答案,我使用了由本地 Rust 开发版本生成的 llc:
% rustc --version --verbose
rustc 1.53.0 (53cb7b09b 2021-06-17)
binary: rustc
commit-hash: 53cb7b09b00cbea8754ffb78e7e3cb521cb8af4b
commit-date: 2021-06-17
host: x86_64-apple-darwin
release: 1.53.0
LLVM version: 12.0.1
% llc --version
LLVM (http://llvm.org/):
LLVM version 12.0.1-rust-dev
Optimized build.
Default target: x86_64-apple-darwin20.5.0
Host CPU: skylake
另见: