How to link with a dylib

Hi dear all,
I'm trying the following code

mylib.rs

pub fn hello() {
  println!("hello Rust");
}

compile it with following command

rustc mylib.rs --crate-type rlib

got a libmylib.rlib, write a test

main.rs

extern crate mylib;
fn main() {
  mylib::hello();
}

comiple this file with following command line

rustc main.rs -L .

it works. then I deleted libmylib.rlib and compile mylib.rs to a dylib

rustc mylib.rs --crate-type dylib

got mylib.dll and mylib.dll.lib, this time the following command failed

rustc main.rs -L .

So how to link to a Rust dynlib ? Many thanks!!!

Try passing -C prefer-dynamic to rustc when compiling both crates. This will make both of them link the standard libraries dynamically, so that you don't end up with conflicting copies.

rustc mylib.rs -C prefer-dynamic --crate-type dylib
rustc main.rs  -C prefer-dynamic -L .    

You will also need to make sure the dynamic linker is able to locate the standard library DLLs when you run your program. (On Windows, I believe you can do this either by copying them to the program directory, or by adding their location to the PATH environment variable.)

1 Like