簡體   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