Confusion behavior when rlib and dylib coexist in the same directory

I have a lib

mylib.rs

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

to rlib

rustc mylib.rs --edition=2018 --crate-type lib

change hello to pub

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

to dylib

rustc mylib.rs -C prefer-dynamic --edition=2018 --crate-type dylib

main.rs

use mylib;
fn main() {
  mylib::hello();
}

to exe

rustc main.rs -C prefer-dynamic --extern mylib --edition=2018 -L .

got private function, but if I delete the rlib and compile again, it will succeed. My question is if prefer-dynamic means

check rlib firstly then dylib

then how to explain this

mylib.rs

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

to rlib

rustc mylib.rs --edition=2018 --crate-type lib

to dylib

rustc mylib.rs -C prefer-dynamic --edition=2018 --crate-type dylib

then

rustc main.rs -C prefer-dynamic --extern mylib --edition=2018 -L .

the final main.exe will still link to mylib.dll. Many thanks!!!

I suspect that it finds and uses the rlib first when compiling, but then uses the dylib when linking.

1 Like