简体   繁体   中英

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

I have 2 files:

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;
}

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 

But the file func.lib is created, so I do:

gcc -o myprog main.c func.lib -lgcc_eh -lshell32 -luserenv -lws2_32 -ladvapi32

But I get an error:

undefined reference to __ms_vsnprintf'

If I do:

rustc --crate-type=staticlib --target=i686-unknown-linux-gnu lib.rs

Then libfunc.a is created, but when I do:

gcc -o myprog main.c libfunc.a

I get an error:

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

What am I doing wrong?

TL;DR: Install a different flavor of GCC

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

Half-informed guessing follows...

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 (or mingw-w64-x86_64-gcc ) does know about Windows-specific symbols, which libbacktrace, a part of the Rust distribution, requires.

The "correct" GCC build should have the string "Built by MSYS2 project" in the gcc --version output.


With that, the full process looks like:

$ 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

sorry for my bad english, to use a static rust library (.lib) you must add the following libraries to your 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

works in visual studio 2022

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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