-
Notifications
You must be signed in to change notification settings - Fork 13.8k
Description
One of my Rust projects consists of a library and a binary. The library can be compiled to WASM but not the binary because one of the binary's dependencies does not support WASM compilation. I tried to disable compilation of the binary for WASM by putting the following attribute at the top-level of the main.rs
file:
// main.rs
#![cfg(not(target_family = "wasm"))]
When compiling for WASM, the following error is thrown by the compiler:
error[E0601]: `main` function not found in crate `grex`
--> src/main.rs:1:2
|
1 |
| ^ consider adding a `main` function to `src/main.rs`
It is not obvious how to handle this error and how to correctly do conditional compilation of binaries. It is not explicitly mentioned in the official Rust docs or I simply could not find it. The only trick that worked for me was to add a second main()
function in the main.rs
file which remains empty. When targeting WASM, this empty main()
function is compiled, otherwise the original first one:
// main.rs
#[cfg(not(target_family = "wasm"))]
fn main() {
// contains the binary-specific code
}
#[cfg(target_family = "wasm")]
fn main() {} // remains empty for the other targets
It would be great if the whole handling of conditional compilation of binaries could be improved. At least, the docs and compiler error message should be improved, stating that two separate conditionally compiled main()
functions are needed if a binary cannot be compiled for all targets. It would be even better to support adding a top-level attribute such as
#![cfg(not(target_family = "wasm"))]
to the main.rs
file so that the binary is not compiled for WASM. Another alternative would be to provide a setting for it in the Cargo.toml
, for instance.
Perhaps you will find ways for improvements in this matter. Thank you for your attention.