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

标签 c windows gcc rust

我有 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'

我做错了什么?

最佳答案

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 输出中包含字符串“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

关于c - 如何在 Rust 中创建静态库以链接到 Windows 中的 C 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43866969/

相关文章:

windows - Tomcat 停止错误

linux - 如何配置 makefile?

c++ - 程序员的错误或 gcc-5.1.0 的错误?

c - 将 GCC 移植到 Multiclet

c - 本书 "c program. lang."版本 2 中的电源程序,循环

c - strlen 给出意外的输出 C

windows - 在运行 Windows XP 的 Intel x86 机器上,内存位置 1 是什么?

windows - 如何自动更改文件内容?

java - 密码破解

c - 求三角形c的最长边