如何在Rust中创建静态库以与Windows中的C代码链接?

Ant*_*kov 9 c windows gcc rust

我有2个文件:

func.rs

#[no_mangle]
pub extern fn double_input(input: i32) -> i32 { input * 2 }
Run Code Online (Sandbox Code Playgroud)

main.c中

#include <stdint.h>
#include <stdio.h>

extern int32_t double_input(int32_t input);

int main() {
   int input = 4;
   int output = double_input(input);
   printf("%d * 2 = %d\n", input, output);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想在Rust中创建静态库并将库链接到main.c. 我的主动工具链是stable-i686-pc-windows-gnu.我在cmd中这样做:

rustc --crate-type=staticlib func.rs 
Run Code Online (Sandbox Code Playgroud)

但是文件func.lib已创建,所以我这样做:

gcc -o myprog main.c func.lib -lgcc_eh -lshell32 -luserenv -lws2_32 -ladvapi32
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误:

undefined reference to __ms_vsnprintf'
Run Code Online (Sandbox Code Playgroud)

如果我做:

rustc --crate-type=staticlib --target=i686-unknown-linux-gnu lib.rs
Run Code Online (Sandbox Code Playgroud)

然后创建libfunc.a,但是当我这样做时:

gcc -o myprog main.c libfunc.a
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

main.c:(.text+0x1e): undefined reference to `double_input'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

She*_*ter 7

TL; DR:安装不同风格的GCC

pacman -R local/gcc
pacman -S mingw-w64-i686-gcc
Run Code Online (Sandbox Code Playgroud)

半知情的猜测跟着......

在Rust IRC的一些帮助之后,听起来问题是MSYS2/MinGW gcc是一个"库存"编译器,没有MSYS/MinGW/Windows特殊功能的专业知识.

mingw-w64-i686-gcc(或mingw-w64-x86_64-gcc)知道Windows的特定符号,这libbacktrace,锈分配的一部分,需要.

"正确的"GCC构建应该在gcc --version输出中包含字符串"由MSYS2项目构建" .


有了这个,整个过程看起来像:

$ rustc --version --verbose
rustc 1.17.0 (56124baa9 2017-04-24)
host: i686-pc-windows-gnu
$ gcc --version
gcc.exe (Rev2, Built by MSYS2 project) 6.3.0

$ rustc --crate-type=staticlib func.rs
note: link against the following native artifacts when linking against this static library
note: the order and any duplication can be significant on some platforms, and so may need to be preserved
note: library: advapi32
note: library: ws2_32
note: library: userenv
note: library: shell32
note: library: gcc_eh
$ gcc -o main main.c func.lib -ladvapi32 -lws2_32 -luserenv -lshell32 -lgcc_eh
$ ./main
4 * 2 = 8
Run Code Online (Sandbox Code Playgroud)