【问题标题】:How do I create a static library in Rust to link with C code in Windows?如何在 Rust 中创建静态库以与 Windows 中的 C 代码链接?
【发布时间】:2017-10-07 14:19:10
【问题描述】:

我有 2 个文件:

func.rs

#[no_mangle]
pub extern fn double_input(input: i32) -> i32 { input * 2 }

ma​​in.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 中这样做:

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'

我做错了什么?

【问题讨论】:

  • gcc -o myprog main.c libfunc.a ---> gcc -lfunc.a main.c -o myprog
  • 如果你使用gcc -o myprog main.c func.lib会发生什么?您在 Windows 上执行所有这些操作,对 - 为什么不在可执行文件上添加 .exe 扩展名?
  • @immibis --target=i686-unknown-linux-gnu 我不认为它在 Windows 上。
  • 那么“我的活动工具链:stable-i686-pc-windows-gnu”——你为什么在 Linux 上使用 Windows 工具链?你想交叉编译吗?
  • @immibis 我尝试在 Linux 中使用 i686-unknown-linux-gnu。如果我使用:gcc -o myprog main.c func.lib,那么我会使用:gcc -o myprog main.c func.lib -lgcc_eh -lshell32 -luserenv -lws2_32 -ladvapi32 但我得到一个错误:undefined reference to __ms_vsnprintf'

标签: c windows gcc rust


【解决方案1】:

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 的符号,而 libbacktrace(Rust 发行版的一部分)需要这些符号。

“正确”的 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

【讨论】:

  • 非常感谢!有用!我简直不敢相信!:)
猜你喜欢
  • 2020-12-16
  • 1970-01-01
  • 2012-02-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
相关资源
最近更新 更多