如何在Rust中创建静态库以与Windows中的C代码链接? [英] How do I create a static library in Rust to link with C code in Windows?
问题描述
我有2个文件:
func.rs
#[no_mangle]
pub extern fn double_input(input: i32) -> i32 { input * 2 }
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;
}
我想在Rust中创建静态库并将库链接到main.c.我的活动工具链是stable-i686-pc-windows-gnu
.我在cmd中这样做:
I want to create static lib in Rust and link the library to main.c. My active toolchain is stable-i686-pc-windows-gnu
. I'm doing this in cmd:
rustc --crate-type=staticlib func.rs
但是文件 func.lib 已创建,所以我这样做:
But the file func.lib is created, so I do:
gcc -o myprog main.c func.lib -lgcc_eh -lshell32 -luserenv -lws2_32 -ladvapi32
但是我得到一个错误:
undefined reference to __ms_vsnprintf'
如果我这样做:
rustc --crate-type=staticlib --target=i686-unknown-linux-gnu lib.rs
然后创建 libfunc.a ,但是当我这样做时:
Then libfunc.a is created, but when I do:
gcc -o myprog main.c libfunc.a
我收到一个错误:
main.c:(.text+0x1e): undefined reference to `double_input'
我在做什么错了?
推荐答案
TL; DR:安装其他风味的GCC
TL;DR: Install a different flavor of GCC
pacman -R local/gcc
pacman -S mingw-w64-i686-gcc
半知半解的猜测随之而来...
Half-informed guessing follows...
在Rust IRC上获得一些帮助之后,听起来好像是MSYS2/MinGW gcc
是一个常规"编译器,没有MSYS/MinGW/Windows特殊功能的专门知识.
After some help on Rust IRC, it sounds like the issue is that the MSYS2 / MinGW gcc
is a "stock" compiler, one without special knowledge of MSYS / MinGW / Windows special features.
mingw-w64-i686-gcc
(或mingw-w64-x86_64-gcc
)确实了解Windows特定的符号,而libbacktrace(Rust发行版的一部分)需要Windows特定的符号.
mingw-w64-i686-gcc
(or mingw-w64-x86_64-gcc
) does know about Windows-specific symbols, which libbacktrace, a part of the Rust distribution, requires.
正确的" GCC构建应在gcc --version
输出中包含字符串由MSYS2项目构建".
The "correct" GCC build should have the string "Built by MSYS2 project" in the gcc --version
output.
这样,整个过程如下:
$ 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
这篇关于如何在Rust中创建静态库以与Windows中的C代码链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!