Is it possible to compile WASM from Rust using C libraries?

I’m attempting to build WASM file from my Rust code which using C library(in particular, a library is sqlite3).

$ cargo build --target wasm32-unknown-emscripten

However, I received an error message from emcc like WARNING:root:emcc: cannot find library "sqlite3"

When I attempt to build code to binary by $ cargo build, rustc can compile it ordinary.
My code looks like below.

// src/main.rs
extern "C" {
    pub fn sqlite3_libversion_number() -> ::std::os::raw::c_int;
}

fn main() {
    println!("Hello with SQLite version {}", unsafe {
        sqlite3_libversion_number()
    });
}

// build.rs
pub fn main() {
  println!("cargo:rustc-link-lib={}", "sqlite3");
  println!(
    "cargo:rustc-link-search={}",
    "/path/to/directory/includes/sqlite3.h"
  );
}

So, my question is, In the first place, is it possible to compile WASM from Rust code which using C libraries?
Moreover if possible, what are things I’m misunderstanding?

1 Like

I’m experiencing the same issue and so far I haven’t found a way to tell cargo that it should pass all the C dependencies to emscripten for compilation. Did you find a solution?

In this case it does pass the C dependencies to emscripten:

emcc: cannot find library "sqlite3"
^^^^^

The problem is that OP tells Rust to link sqlite3 library, but there isn’t one at the path they’ve provided. sqlite3.h is not a library, and the linker can’t do anything with it. The linker won’t use .c files either.

To use rustc-link-lib you must have a WASM version of sqlite3 library already compiled. It has to be specifically a WASM library, and it can’t be the native system version that you may have somewhere on the system already.

Alternatively, you could try building sqlite from source with the cc crate. I’ll handle linking as a static library for you.

2 Likes

How do you make a WASM library? Is that a WASM library compiled as a cdylib?