/Rust doesn't support implict linking?

hello, i am wonder rust support impict linking.

You can use dll by implicitly linking it through the import library in cpp.

When building with dylib in Rust, .lib and dll files are output. Can't implicit linking be done with these like with cpp?

i need your help
thanks.

you cannot link crate-type=dylib for C++, use crate-type=cdylib instead. dylib is only for rust.

thanks for replying

What I mean is, I want to build it as dylib and use it only in rust. Is that possible??

in build.rs

fn main() {
    // DLL 라이브러리 경로 설정
    println!("cargo:rustc-link-search=all=D:/work/rust/test/rust_20250318/target/debug/");
    println!("cargo:rustc-link-lib=dylib=rust_20250318");
}

but this doesn't compile...

why don't you just use it as a dependency crate then?

direct linker directives are generally for native libraries. even if the linker find the library file, it may not be able to resolve the rustc mangled symbols. the correct way to link a rust library is use it as a crate.

in order to do this, you need set the --extern rust flag directly, either with RUSTFLAGS env variable or the build.rustflags setting in .cargo/config.toml, there's no equivalent in the build script.

disclaimer: it should work for .rlib and .so (.dll on Windows) file, but I don't know if it will work for the import .lib file though.

for example, suppose you built the foo library at /foo/target/debug/libfoo.so, which export a function hello:

// /foo/src/lib.rs
pub fn hello() {
    println!("hello from libfoo");
}

and use it in bar like this:

// /bar/src/main.rs
extern crate foo;
use foo::hello;
fn main() {
    hello();
}

to compile bar, you pass the --extern command line option to rustc:

/bar $ rustc -L/foo/target/debug --extern foo src/main.rs -o target/debug/bar

or alternative:

/bar $ rustc --extern foo=/foo/target/debug/libfoo.so src/main.rs -o target/debug/bar

when building crate-type=dylib, be sure to use -C prefer-dynamic, otherwise, you may get link problems for the standard library.


ps. I think the -l linker flags can work in theory, if you import the symbols properly, but I didn't test it.

1 Like