rustwebassemblyrust-wasm

Why I cannot find the compiled wasm file?


I am new to the WASM world. I tried to create a really simple rust lib that only contains add function and wants to compile it to the .wasm. I already know that the wasm-pack can achieve this. But why the cargo build --target wasm32-unknown-unknown --release can not?

// Cargo.toml
[package]
name = "hello-wasm"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
// lib.rs
pub fn add(left: usize, right: usize) -> usize {
    left + right
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}

The compiled target folder:

$ ls target/wasm32-unknown-unknown/release/                 
build/  deps/  examples/  incremental/  libhello_wasm.d  libhello_wasm.rlib

Expected there is a file named hello-wasm.wasm.


Solution

  • With a lib.rs and no customization, you've defined a Rust library. By default, Cargo compiles libraries to .rlib files which can then be used as inputs when compiling crates that depend on this one.

    In order to get a .wasm file, you must request a crate-type of cdylib in your configuration (and this is also standard when using wasm-pack):

    [lib]
    crate-type = ["cdylib"]
    

    If you want the library to also be usable in tests and as a dependency, then you should specify the default mode "lib" too:

    [lib]
    crate-type = ["lib", "cdylib"]
    

    (cdylib stands for "C dynamic library" — a WASM module is kind of like a dynamic library, and "C" should be understood as just meaning "native format, no Rust-specific conventions".)