因为官方文档不太完善,踩了坑,所以将正确的流程写下来

配置WasmEdge和Rust:

  1. 安装rust(使用curl --proto '=https' --tlsv1.2 -sSf <https://sh.rustup.rs> | sh下载Rust,不要使用Homebrew!)

  2. 下载wasm(需要python):

    curl -sSf <https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh> | bash
    

    (可能要尝试多次)

  3. 使用cargo new hello-wasm 新建项目,将以下这些行添加到项目目录下的**.cargo/config**.toml文件中:

    [build]
    target = "wasm32-wasi"
    rustflags = ["--cfg", "wasmedge", "--cfg", "tokio_unstable"]
    
  4. 使用rustup target add wasm32-wasi添加编译器目标

  5. 如果是macOS,需要在https://github.com/WebAssembly/wasi-sdk/releases下载特殊版本的 Clang 工具,以支持Rust TLS 库

    1. ./.zshrc文件中添加环境变量:

      export WASI_SDK_PATH /path/to/wasi-sdk-version
      export CC="${WASI_SDK_PATH}/bin/clang --sysroot=${WASI_SDK_PATH}/share/wasi-sysroot"
      
    2. 使用${WASI_SDK_PATH}/bin/clang —-verion判断是否设置成功,可能要在设置中允许“不明开发者的程序”,可以cd进WASI_SDK_PATH之后运行xattr -dr com.apple.quarantine .来移除所有可执行文件的“不受信任的来源下载”属性

  6. 创建并编辑main.rs

    fn main() {
      let s : &str = "Hello WasmEdge!";
      println!("{}", s);
    }
    
  7. 运行cargo build --target wasm32-wasi --release编译项目

  8. 运行wasmedge target/wasm32-wasi/release/hello-wasm.wasm,终端输出Hello WasmEdge,成功

注意,之后想要使用系统默认的Clang,需要unset CC && unset CXX