我如何生成由Rust编写且已编译为LLVM-IR位代码的应用程序的可执行文件?
如果我尝试使用rustc编译 .bc 文件,它会告诉我 流不包含有效的UTF-8
,我似乎找不到rustc中是否有特定的选项可以解决这个问题。
基本上,我想实现以下操作:
program.rs
-> program.bc
-> program
。
其中 program
是最终的可执行文件。我应该采取哪些步骤来实现这一点?
从这个源代码开始:
fn main() {
println!("Hello, world!");
}
# 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
DYLD_LIBRARY_PATH
,因为我动态链接到了Rust标准库,而这个库不在我的常规库搜索路径中。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
还可以参考:
-l
标志的工作原理。它会在前面加上 lib
并添加 .dylib
(或 .so
,或适用于该平台的任何内容)。 - ShepmasterLLVM文档非常晦涩,所以并不明显,但是 clang 可以编译LLVM IR文件(“.ll”)和bitcode文件(“.bc”),并链接您的系统库。
在具有Rust 1.9的Linux上:
clang -dynamic-linker /usr/local/lib/rustlib/x86_64-unknown-linux-gnu/lib/libstd-d16b8f0e.so hello.ll -o hello
rustc
是 Rust 编译器,它不会编译其他输入格式。如果您有位码,为什么不使用 LLVM 的llc
或等效工具呢? - Shepmaster