我正在尝试使用带有 GCC 4.9.3 和 Rust 1.9.0 稳定版的 MinGW 在 Windows 中构建一个调用 Rust 函数的 C 简单应用程序。这是源代码:
测试.rs
#![crate_type = "staticlib"]
#[no_mangle]
pub extern "C" fn get_number() -> isize {
42 as isize
}
Run Code Online (Sandbox Code Playgroud)
主文件
#include <stdio.h>
int get_number();
int main()
{
printf("Hello, world!\n");
printf("Number is %d.\n", get_number());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在,我知道我应该在 Rust 等中使用 C 兼容类型。但是在进入程序正确性之前,有一个问题是 Rust 似乎正在生成 GCC 不理解的目标文件。这是我正在尝试的:
rustc --emit obj test.rs
gcc -c main.c
gcc -static-libgcc test.o main.o -lmingw32 -o test.exe
Run Code Online (Sandbox Code Playgroud)
但是链接器命令以:
test.o: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
我搜索了会改变输出格式的 Rust 编译器指令,但我找不到任何。我读过 Rust 的 FFI 文档,但它没有提到类似的内容。通常,信息是关于从 Rust 调用 C。as显然,由于语法不兼容,要求 Rust 生成 ASM 文件并使用 GCC 进行组装是行不通的。
这是与 Windows 版本的 Rust/GCC 的兼容性问题吗?我可以做些什么来从 Rust 生成兼容的目标文件?或者更确切地说,我应该要求 Rust 生成什么样的输出才能使这成为可能?我也对在各种游戏控制台 SDK 上从 C 调用 Rust 代码感兴趣。我需要什么样的设置才能最大限度地提高与其他链接器的兼容性?
对我来说很好用:
$ rustc test.rs --emit=obj
$ gcc -c main.c
$ file test.o
test.o: 80386 COFF executable not stripped - version 30821
$ file main.o
main.o: 80386 COFF executable not stripped - version 30821
$ gcc test.o main.o -o awesome
$ file awesome.exe
awesome.exe: PE32 executable (console) Intel 80386, for MS Windows
$ ./awesome.exe
Hello, world!
Number is 42.
$ rustc --version --verbose
rustc 1.9.0 (e4e8b6668 2016-05-18)
binary: rustc
commit-hash: e4e8b666850a763fdf1c3c2c142856ab51e32779
commit-date: 2016-05-18
host: i686-pc-windows-gnu
release: 1.9.0
$ gcc --version
gcc (GCC) 5.3.0
Run Code Online (Sandbox Code Playgroud)