繁体   English   中英

如何在 Rust 中创建 static 库以与 ZAEA23489CE3AA9B6406EBA4 中的 C 代码链接?

[英]How do I create a static library in Rust to link with C code in Windows?

我有 2 个文件:

函数

#[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 中创建 static 库并将库链接到 main.c。 我的活动工具链是stable-i686-pc-windows-gnu 我在 cmd 中这样做:

rustc --crate-type=staticlib func.rs 

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

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 ,但是当我这样做时:

gcc -o myprog main.c libfunc.a

我收到一个错误:

main.c:(.text+0x1e): undefined reference to `double_input'

我究竟做错了什么?

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

pacman -R local/gcc
pacman -S mingw-w64-i686-gcc

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

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

mingw-w64-i686-gcc (或mingw-w64-x86_64-gcc确实了解特定于Windows的符号,这是Rust发行版所需的libbacktrace。

“正确的”GCC构建应该在gcc --version输出中包含字符串“Built by MSYS2 project”。


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

$ 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

抱歉我的英语不好,要使用 static rust 库 (.lib),您必须将以下库添加到 linker 中:

  • shell32.lib advapi32.lib cfgmgr32.lib comctl32.lib comdlg32.lib d2d1.lib dwrite.lib dxgi.lib gdi32.lib kernel32.lib msimg32.lib ole32.lib opengl32.lib shlwapi.lib user32.lib windowscodecs.lib winspool。 lib userenv.lib ws2_32.lib bcrypt.lib msvcrt.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib

在视觉工作室 2022 工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM