Rust and C compatibility with Visual Studio

Is it possible to create a static library compiled with rustc and link it to an executable compiled using MSVC?

+4
source share
1 answer

If you want to use it only rustcto create a static library, you will do this by specifying some attributes in your crate file lib.rsand marking the exported functions as follows:

#![crate_type = "static_lib"]
#![crate_name = "mylib"]

use libc::c_int;

#[no_mangle]
pub extern fn my_exported_func(num: c_int) -> c_int {
    num + 1
}

Then just call rustc lib.rs. This applies to all platforms supported rustc.

In the C / C ++ header add:

#pragma once

// only use extern block if the header is put inside a C++ CU
extern "C" {
    int my_exported_func(int num);
}

and if necessary, link the output .libor .a.

For Cargo, you can specify the type and name of the box in Cargo.toml.

Sources:

+1

All Articles